单元测试了解
# 单元测试了解
测试文件以 _test.go 结尾,测试函数以 Test 开头。表驱动测试适合集中覆盖正常值、边界值和失败路径。
func TestLevel(t *testing.T) {
tests := []struct {
input int
want string
}{{99, "fast"}, {100, "normal"}, {-1, "invalid"}}
for _, test := range tests {
if got := level(test.input); got != test.want {
t.Fatalf("level(%d) = %q, want %q", test.input, got, test.want)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
使用 go test ./... 运行测试,go test -race ./... 检查竞态,go test -cover ./... 查看覆盖率。覆盖率不能替代对超时、取消、资源关闭和错误链的行为验证。