...

/

Testing: A Concrete Example

Testing: A Concrete Example

This lesson brings an application to test according to the concepts learned in the last lesson.

We'll cover the following...

Here is a concrete example for you to run and learn to test:

package even
import "testing"

func TestEven(t *testing.T) {
    if !Even(10) {
        t.Log(" 10 must be even!")
        t.Fail()
    }
    if Even(7) {
        t.Log(" 7 is not even!")
        t.Fail()
    }
}

func TestOdd(t *testing.T) {
    if !Odd(11) {
        t.Log(" 11 must be odd!")
        t.Fail()
    }
    if Odd(10) {
        t.Log(" 10 is not odd!")
        t.Fail()
    }
}

This is our test program: it imports the even package at line 4, which will contain the functional logic and the tests. Then, we have for-loop at line 8 controlling 100 iterations. It shows the first 100 integers and whether they are even or not (see line 9).

The package even in the subfolder even contains the logic in the two functions Even and Odd. The Even function returns true if an integer i passed to it is even (i%2 == 0). The Odd function returns true if an integer i passed to it is not even (i%2 != 0).

The file oddeven_test.go contains the tests. It belongs to the package even ( ...