4、测试与性能调优


testing 实现 表格驱动测试

main.go

package main

func Add(a,b int) int {
    return a + b
}

func main()  {
    
}

add_test.go

package main

import "testing"

func TestAdd(t *testing.T) {
    tests := []struct{ a,b,c int} {
        {1,2,3},
        {1,5,3},
        {3,3,6},
    }

    for _,tt := range tests{
        if res := Add(tt.a,tt.b); res != tt.c{
            t.Errorf("计算错误:%d + %d = %d,而不是 %d",tt.a,tt.b,res,tt.c)
        }
    }
}

利用编辑器测试 

命令行测试

cd test
go test .

代码覆盖率测试

ide检测

命令行检测

go test -coverprofile=c.out
go tool cover -html=c.out

代码性能测试

func BenchmarkAdd(b *testing.B) {
    var a,aa int
    a = 1000
    aa = 2000

    for i := 0; i < b.N; i++ {
        if res := Add(a,aa); res != 3000{
            b.Errorf("计算错误:%d + %d = %d,而不是 %d",a,aa,res,3000)
        }
    }
}

ide测试

代码测试

go test -bench .

利用 pprof 进行性能调优

安装 Graphviz

查看性能

go test -bench . -cpuprofile cpu.out
go tool pprof cpu.out
web

TODO:http 测试

TODO:注释写文档,godoc 查看文档

TODO:测试中加入 Example

相关