Test with failure


The previous test was great, but soon people will report that the add function does not always work. In fact they will report it never works properly. If you are lucky they will also supply you with a case for which it did not work properly so you can try to reproduce the problem. You do that by writing another test case:

The code is still the same:


examples/test-fail/comp2.go
package main

import (
    "fmt"
)

func main() {
    res := add(2, 2)
    fmt.Println(res)
}

func add(a, b int) int {
    return a * b
}

But now we have two separate test cases:


examples/test-fail/comp2_test.go
package main

import "testing"

func TestAdd1(t *testing.T) {
    t.Log("Hello from the test")
    total := add(2, 2)
    if total != 4 {
        t.Error("Sum was incorrect")
    }
}

func TestAdd2(t *testing.T) {
    t.Log("Hello from the test")
    total := add(3, 3)
    if total != 6 {
        t.Errorf("expected 6 received %v", total)
    }
}

If we run the tests now:


go test

We get a failure report in which we can see the line number of the failure and the message. If we prepare our message well, then wen can immediately see the actual value and the expected value that might be able to help us locate the problem.


examples/test-fail/test2.out
--- FAIL: TestAdd2 (0.00s)
    comp2_test.go:14: Hello from the test
    comp2_test.go:17: expected 6 received 9
FAIL
exit status 1
FAIL	_/home/gabor/work/slides/golang/examples/test-fail	0.002s

If this is not enough we can ask for more verbose output:


go test -v


examples/test-fail/test2_v.out
=== RUN   TestAdd1
    TestAdd1: comp2_test.go:6: Hello from the test
--- PASS: TestAdd1 (0.00s)
=== RUN   TestAdd2
    TestAdd2: comp2_test.go:14: Hello from the test
    TestAdd2: comp2_test.go:17: expected 6 received 9
--- FAIL: TestAdd2 (0.00s)
FAIL
exit status 1
FAIL	_/home/gabor/work/slides/golang/examples/test-fail	0.002s