在Go语言中写单元测试

先创建一个目录,例如:

~/foo/go/unit-test

创建两个文件:

$ ls
sum.go  sum_test.go
$ cat sum.go
package some_package

func Sum(x int, y int, z int) int {
    return x + y + y    <- 故意写错的
}
$ cat sum_test.go 
package some_package

import (
    "testing"
)

type TestData struct {
    x, y, z, exp int
}

var testTable = []TestData {
    {1,2,2,5},
    {3,4,5,12},
    {100,1000,1000,2100},
}

func TestSum(t *testing.T) {
    for _, d := range testTable {
        total := Sum(d.x, d.y, d.z)
        if total != d.exp {
            t.Errorf("%d+%d+%d=%d, expect %d", d.x, d.y, d.z, total, d.exp)
        } else {
            t.Logf("%d+%d+%d=%d, correct", d.x, d.y, d.z, total)
        }
    }
}

启动单元测试:

$ go test
--- FAIL: TestSum (0.00s)
    sum_test.go:23: 1+2+2=5, correct
    sum_test.go:21: 3+4+5=11, expect 12
    sum_test.go:23: 100+1000+1000=2100, correct
FAIL
exit status 1
FAIL    _/home/louyang/foo/go/unit-test 0.002s

你可能感兴趣的:(在Go语言中写单元测试)