main.go:
package main import ( "fmt" ) func main() { fmt.Println(Sum(4,5)) } func Sum(a, b int) int { return a + b }
main_test.go:
package main import ( "testing" ) // 测试方法以“ Test”开始 func TestSum(t *testing.T) { got := Sum(1, 2) want := 3 if got != want { t.Errorf("Sum(1, 2) == %d, want %d", got, want) } }
要运行测试,只需使用以下go test命令:
$ go test ok test_app 0.005s
使用该-v标志查看每个测试的结果:
$ go test -v === RUN TestSum --- PASS: TestSum (0.00s) PASS ok _/tmp 0.000s
使用该路径./...以递归方式测试子目录:
$ go test -v ./... ok github.com/me/project/dir1 0.008s === RUN TestSum --- PASS: TestSum (0.00s) PASS ok github.com/me/project/dir2 0.008s === RUN TestDiff --- PASS: TestDiff (0.00s) PASS
运行特定测试:
如果有多个测试,并且您想运行特定测试,则可以这样进行:
go test -v -run=<TestName> // 将仅使用此名称执行测试
例:
go test -v run=TestSum