$ go test demo_test.go demo.go # 单元测试$ go test --cover demo_test.go demo.go # 单元测试覆盖率$ go test -bench=. demo_test.go demo.go # 性能测试
简单测试:
go
1
2
3
4
5
6
funcTestAddSimple(t *testing.T) {
expect, actual :=3, Add(1, 2)
if expect != actual {
t.Errorf("预期:%d,实际:%v", expect, actual)
}
}
表格驱动: - 功能测试主要以表格驱动测试为主
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcTestMethodName(t *testing.T) {
for _, unit :=range []struct {
param1 string//参数1 param2 string//参数1 expect string//期望结果 }{
{"hello", "world", "hello world"},
{"hello", "golang", "hell_golang"},
} {
if actual :=func(x, y string) string { return x + y }(unit.param1, unit.param2);
actual != unit.expect {
t.Errorf("期望:[%v],实际:[%v]", unit.expect, actual)
}
}
}
主函数
#二. 基准测试
测试函数须以BenchmarkFoo(b *testing.B)
b.N即运行次数,会根据运行时间自动取值
执行结果27.9 ns/op, 即平均每次27.9纳秒
并发测试即对象或函数在多线程下是否安全
并发测试:
go
1
2
3
4
5
funcBenchmarkAdd(b *testing.B) {
for i :=0; i < b.N; i++ {
Add(i+1, rand.Intn(i+1))
}
}
并发测试:
go
1
2
3
4
5
6
7
8
9
funcBenchmarkAddParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
m := rand.Intn(100) +1 n := rand.Intn(m)
Add(m, n)
}
})
}
覆盖率
指测试用例能覆盖到到代码比率
go
1
2
3
4
5
6
7
8
9
10
11
//业务代码: 成绩评级funcRating(x int) string {
switch {
case x < 60:
return"flunk"case x < 80:
return"pass"default:
return"excellent" }
}
go
1
2
3
4
5
6
7
8
9
10
// 测试用例funcTestDiv(t *testing.T) {
if r :=Rating(50); r !="flunk" {
t.Errorf("实际:%v", r)
}
if r :=Rating(85); r !="excellent" {
t.Errorf("实际:%v", r)
}
//没考虑到<80的情况}
shell
1
2
3
4
[sybs@hello] $ go test --cover
PASS
coverage: 75.0% of statements
ok hello 0.005s
评论