文件名必须以_test.go结尾
使用go test 执行单元测试
package main
func add(a, b int) int {
return a + b
}
func sub(a, b int) int {
return a - b
}
calc.go
package main
import (
"testing"
)
func TestAdd(t *testing.T) {
r := add(2, 4)
if r != 6 {
t.Fatalf("add(2,4) error,expect:%d,actual:%d", 6, r)
}
t.Logf("test add succ")
}
func TestSub(t *testing.T) {
r := sub(2, 4)
if r != -2 {
t.Fatalf("sub(2,4) error,expect:%d,actual:%d", 6, r)
}
t.Logf("test sub succ")
}
calc_test.go
package main
main.go
E:\project\src\go_dev\day8\test>go test -v
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
calc_test.go:13: test add succ
=== RUN TestSub
--- PASS: TestSub (0.00s)
calc_test.go:20: test sub succ
PASS
ok go_dev/day8/test 0.142s