测试
Test 代码测试
func TestAdd(t *testing.T) {
tests := []struct{a, b, c int}{
{1, 2, 3},
{4, 5, 6},
{123, 345, 468},
{1, 345, 468},
}
for _, tt :=range tests{
if actual := add(tt.a, tt.b); actual!=tt.c{
t.Errorf("add(%d, %d); get %d; expected %d\n", tt.a, tt.b, actual, tt.c)
}
}
}
Benchmark 性能测试
性能数据分析
测试代码
func BenchmarkAdd(b *testing.B){
inA, inB:=123, 345
outC:=468
// 之前操作不计入计时
b.ResetTimer()
for i:=0;i<b.N;i++ {
actual := add(inA, inB)
if actual != outC {
b.Errorf("add(%d, %d); get %d; expected %d\n",
inA, inB, actual, outC)
}
}
}
命令行操作
// 运行测试
go test -bench . -cpuprofile cpu.out
// 分析输出的测试数据文件`cpu.out`
go tool pprof cpu.out
// 交互页面输入web生成svg分析数据
// 需要下载工具并配置环境变量