表格驅(qū)動(dòng)測(cè)試
表格驅(qū)動(dòng)測(cè)試的優(yōu)勢(shì)
- 分離的測(cè)試數(shù)據(jù)和測(cè)試邏輯
- 明確的出錯(cuò)信息
- 可以部分失敗
- go 語(yǔ)言的語(yǔ)法使得我們更易實(shí)踐表格驅(qū)動(dòng)測(cè)試
func TestTriangle(t *testing.T) {
tests := []struct{ a, b, c int} {
{3, 4, 5},
{5, 12, 13},
{8, 15, 17},
{12, 35, 0},
{30000, 40000, 50000},
}
for _, tt := range tests {
if actual := calcTriangle(tt.a, tt.b); actual != tt.c {
t.Errorf("calcTriangle(%d, %d); " + "got %d; expected %d", tt.a, tt.b, actual, tt.c)
}
}
}
func calcTriangle(a, b int) int {
var c int
c = int(math.Sqrt(float64(a * a + b * b)))
return c
}
benchmark 示例
這里我們不需要指定一個(gè)循環(huán)的循環(huán)次數(shù),go 會(huì)幫我們做好的
func BenchmarkSubstr(b *testing.B) {
s := "黑化肥揮發(fā)發(fā)灰會(huì)花飛灰化肥揮發(fā)發(fā)黑會(huì)飛花"
ans := 8
for i := 0; i < b.N; i++ {
actual := lengthOfNonRepeatingSubStr(s)
if actual != ans {
b.Errorf("got %d for input %s;"+"expected %d", actual, s, ans)
}
}
}
命令行測(cè)試常用指令
運(yùn)行測(cè)試文件
go test .
查看代碼覆蓋率
go tool cover -html=c.out
運(yùn)行benchmark
go test -bench .
查看cpu占用,來優(yōu)化代碼
go test -bench . -cpuprofile cpu.out
go tool pprof cpu.out
> web
查看文檔
godoc -http: 6060