測試
go語言測試文件命名:name_test.go,編譯器就是識別這個測試文件。
go test . 執行當前目錄下的測試文件。
func TestSubStr(t *testing.T) {
//表格驅動測試
tests := []struct {
s string
ans int
}{
//Normal cases
{"abcabcabc", 3},
{"pwwkew", 3},
//Edge cases
{"", 0},
{"abcabcabcd", 4},
{"bbbbbb", 1},
{"b", 1},
//Chinese support
{"這是慕課網", 5},
{"一二三二一", 3},
}
for _, tt := range tests {
//輸出錯誤信息
if actual := lengthOfNonRepeatingSubStr(tt.s); actual != tt.ans {
t.Errorf("got %d for input %s; expected %d", actual, tt.s, tt.ans)
}
}
}
代碼覆蓋率和性能測試
go test -coverprofile=c.out //測試代碼覆蓋率
go tool cover -html=c.out //查看覆蓋的代碼
go test -bench . //性能測試
func BenchmarkSubstr(b *testing.B) {
s, ans := "一二三二一", 3
//b.N是運行多少次,系統自己設置
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)
}
}
}
使用pprof進行性能調優
go test -bench . -cpuprofile=cpu.out
go tool pprof cpu.out //查看cpu.out文件
web //查看性能,方塊越大,性能損壞越嚴重
生成文檔
go doc fmt.Println //查看文檔
godoc -http :8888 //可以查看自己的代碼文檔。使用註釋寫文檔
godoc -url "http://localhost:6060/pkg/learnGo/queue/">page.html //保存某一頁
還可以在test文件中寫實例代碼,在文檔中也可以看到。
func ExampleQueue_Pop() {
q := Queue{1}
q.Push(1)
q.Push(2)
fmt.Println(q.Pop())
fmt.Println(q.Pop())
// output:
//1
//1
}