Go: 8-1 测试

传统测试
表格驱动测试
tests := []struct{
    a,b,c int32
}{
    {1,2,3},
    {0,2,2},
    {0,0,0},
    {-1,1,0},
    {Integer.MaxInt32,1,Integer.MinInt32},
}
for _,test := range tests{
    if actual := add(test.a,test.b);actual != text.c{
    }
}

测试代码覆盖率和性能测试

func lengthOfNonRepeatingSubStr(s string) int {
	lastOccurred := make(map[rune]int)
	start := 0
	maxLength := 0

	for i, ch := range []rune(s) {
		if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
			start = lastI + 1
		}
		if i-start+1 > maxLength {
			maxLength = i - start + 1
		}
		lastOccurred[ch] = i
	}

	return maxLength
}
------------------------------------------------------------

//在package目录下 执行命令 可以执行当前包下的所有测试用例
go test .

//测试代码覆盖率
go test -coverprofile=c.out


func TestSubstr(t *testing.T) {
	tests := []struct {
		s   string
		ans int
	}{
		// Normal cases
		{"abcabcbb", 3},
		{"pwwkew", 4},

		// Edge cases
		{"", 0},
		{"b", 1},
		{"bbbbbbbbb", 1},
		{"abcabcabcd", 4},

		// Chinese support
		{"这里是慕课网", 6},
		{"一二三二一", 3},
		{"黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花", 9},
	}
	for _, tt := range tests {
		actual := lengthOfNonRepeatingSubStr(tt.s)
		if actual != tt.ans {
			t.Errorf("got %d for input %s; "+
				"expected %d",
				actual, tt.s, tt.ans)
		}
	}
}



//性能测试
go test -bench .
func BenchmarkSubstr(b *testing.B) {
	s := "黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"
	for i := 0; i < 13; i++ {
		s = s + s
	}
	b.Logf("len(s) = %d", len(s))
	ans := 9
	b.ResetTimer()

	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进行性能调优
//生成cpu.out 二进制文件,无法直接查看
go test -bench . -cpuprofile cpu.out 
//可以使用
go tool pprof cpu.out 
//进入pprof 工具命令行解码

$ go tool pprof cpu.out 
Type: cpu
Time: Mar 2, 2018 at 12:06pm (CST)
Duration: 2.52s, Total samples = 2.09s (83.09%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) web  // 若没有安装graphviz 需要 安装 brew install graphviz  

//打开web页面 image