测试
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
}