首先创建源码文件并实现方法。
func IntMin(a, b int) int {
if a < b {
return a
}
return b
}
然后创建测试文件并实现测试方法。测试文件的文件名一般是源码文件名加_test
后缀。
func TestIntMinBasic(t *testing.T) {
ans := IntMin(2, -2)
if ans != -2 {
t.Errorf("IntMin(2, -2) = %d; want -2", ans)
}
}
func TestIntMinTableDriven(t *testing.T) {
var tests = []struct {
a, b int
want int
}{
{0, 1, 0},
{1, 0, 0},
{2, -2, -2},
{0, -1, -1},
{-1, 0, -1},
}
for _, tt := range tests {
testname := fmt.Sprintf("%d, %d", tt.a, tt.b)
t.Run(testname, func(t *testing.T) {
ans := IntMin(tt.a, tt.b)
if ans != tt.want {
t.Errorf("got %d, want %d", ans, tt.want)
}
})
}
}
func BenchmarkIntMin(b *testing.B) {
for i := 0; i < b.N; i++ {
IntMin(1, 2)
}
}
命令行输入:
go test -v
命令行输出:
=== RUN TestIntMinBasic
— PASS: TestIntMinBasic (0.00s)
=== RUN TestIntMinTableDriven
=== RUN TestIntMinTableDriven/0,1
=== RUN TestIntMinTableDriven/1,0
=== RUN TestIntMinTableDriven/2,-2
=== RUN TestIntMinTableDriven/0,-1
=== RUN TestIntMinTableDriven/-1,_0
— PASS: TestIntMinTableDriven (0.00s)
— PASS: TestIntMinTableDriven/0,1 (0.00s)
— PASS: TestIntMinTableDriven/1,0 (0.00s)
— PASS: TestIntMinTableDriven/2,-2 (0.00s)
— PASS: TestIntMinTableDriven/0,-1 (0.00s)
— PASS: TestIntMinTableDriven/-1,_0 (0.00s)
PASS
ok _/Users/baiye/Documents/Golang/Examples/Testing_and_Benchmarking 0.006s
命令行输入:
go test -bench=.
命令行输出:
goos: darwin
goarch: amd64
cpu: Intel® Core™ i5-4308U CPU @ 2.80GHz
BenchmarkIntMin-4 1000000000 0.3730 ns/op
PASS
ok _/Users/baiye/Documents/Golang/Examples/Testing_and_Benchmarking 0.423s