测试及调优
传统测试
assert
缺点:测试数据和逻辑混合在一起
出错信息不明确
一旦一个数据出错测试全部结束表格驱动测试
优点:分离的测试数据和测试逻辑
明确的出错信息
可以部分失败测试编写
将测试文件和源码放在相同目录下
结果测试函数以Test开头,参数为testing.T,并且不能返回任何值
性能测试函数以Benchmark开头,参数为testing.B,并且不能返回任何值1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43//func TestXXXX(t *testing.T){}
//funcs.go
func Add(a, b int) int {
return a + b
}
//add_test.go
func TestAdd(t *testing.T) {
tests := []struct {
a, b, c int
}{
{1, 2, 3},
{3, 4, 7},
{math.MaxInt64, 1, math.MinInt64},
{math.MaxInt64, 1, 0},
}
for _, i := range tests {
if actual := funcs.Add(i.a, i.b); actual != i.c {
t.Errorf("%d+%d return: %d realvalue: %d", i.a, i.b, actual, i.c)
}
}
}
/*
9223372036854775807+1 return: -9223372036854775808 realvalue: 0
*/
func BenchmarkAdd(b *testing.B) {
s := Add(math.MaxInt64, 1)
ans := math.MinInt64
for i := 0; i < b.N; i++ {
if s != ans {
b.Errorf("%d %d", s, ans)
}
}
}
/*
goos: darwin
goarch: amd64
pkg: study/tests/funcs
2000000000 0.66 ns/op
PASS
coverage: 100.0% of statements
*/也可以使用命令行启动测试
1
2
3go test .
go test -bench .
go test . -coverprofile c.out #可以生成cover详情文件pprof 性能调优
1
go test -bench . -cpuprofile cpu.out #可以生成耗时详情文件
go tool
1
2go tool cover -html c.out #可以以html查看c.out
go tool pprof cpu.out #可以查看耗时详情文件
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 SHIELD!
评论