Skip to content
On this page

测试与基准

文件与函数约定

  • 测试文件 *_test.go,与包同目录。
  • func TestXxx(t *testing.T)Xxx 不以小写字母开头。
  • 同包测试:package foo;外部测试(黑盒):package foo_test,仅导出 API 可见。

表驱动测试

go
func TestAbs(t *testing.T) {
    tests := []struct {
        name string
        in   int
        want int
    }{
        {"neg", -1, 1},
        {"zero", 0, 0},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Abs(tt.in); got != tt.want {
                t.Fatalf("Abs(%d) = %d, want %d", tt.in, got, tt.want)
            }
        })
    }
}

t.Run 支持子测试与并行 t.Parallel()(注意数据竞争:勿共享可变状态)。

模糊测试(Go 1.18+)

go
func FuzzReverse(f *testing.F) {
    f.Add("a", "b")
    f.Fuzz(func(t *testing.T, a, b string) {
        // 属性:Reverse(Reverse(s)) == s 等
    })
}

go test -fuzz=FuzzReverse 运行;语料写入 testdata/fuzz/...

基准

go
func BenchmarkFoo(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Foo()
    }
}

go test -bench=. -benchmem;对比时用 -count 多次取稳定结果。避免在循环外做应计入的初始化除非用 b.ResetTimer()

覆盖率

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

httptest

对 HTTP 处理器使用 httptest.NewRecorder + NewRequest,无需真实端口。

pprof

import _ "net/http/pprof" 在服务端注册调试路由;或基准 memprofile/cpuprofile。生产环境须限制访问。

-short

长耗时集成测试用 if testing.Short() { t.Skip() },CI 快速路径传 -short

技术文库