Go 通过 testing package 和 go test 命令提供内置测试——无需外部框架。测试位于 _test.go 文件中,Go 强调表驱动测试、基准测试和优秀的工具作为一流特性。
基本测试
go
{ a + b }
{
result := Add(, )
result != {
t.Errorf(, result)
}
}
Go 通过 testing package 和 go test 命令提供内置测试——无需外部框架。测试位于 _test.go 文件中,Go 强调表驱动测试、基准测试和优秀的工具作为一流特性。
{ a + b }
{
result := Add(, )
result != {
t.Errorf(, result)
}
}
测试函数以 Test 开头,接收 *testing.T,并通过 t.Errorf/t.Fatalf 报告失败。没有断言关键字——你用普通的 if 检查条件并报告失败(Go 倾向于这种显式风格)。
func TestAdd(t *testing.T) {
tests := []struct { // a table of test CASES
name string
a, b int
expected int
}{
{"positives", 2, 3, 5},
{"with zero", 0, 5, 5},
{"negatives", -1, -1, -2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { // a SUBTEST per case (named, isolated)
if got := Add(tt.a, tt.b); got != tt.expected {
t.Errorf("Add(%d,%d) = %d; want %d", tt.a, tt.b, got, tt.expected)
}
})
}
}
表驱动测试是 Go 的主流习语——定义一个 case 切片,使用 t.Run 子测试循环遍历。这使添加 case 变得简单,并为每个 case 提供清晰的单独通过/失败报告。
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ { // the framework chooses b.N for statistical accuracy
Add(2, 3)
}
}
// go test -bench=. → reports ns/op (and -benchmem for allocations)
go test -cover # coverage percentage
go test -coverprofile=c.out # then: go tool cover -html=c.out (visual report)
go test -race # the RACE DETECTOR — finds data races (crucial for concurrency)
go test -run TestAdd # run specific tests
-race 标志特别重要——它检测并发代码中的数据竞争,鉴于 Go 对并发的关注,这是一个关键工具。
func TestMain(m *testing.M) { // package-level setup/teardown
setup()
code := m.Run()
teardown()
os.Exit(code)
}
// t.Helper() marks a function as a test helper (better failure line reporting)
// httptest package for testing HTTP handlers; interfaces for mocking dependencies
测试是 Go 中的一流、内置部分——testing package 和 go test 无需外部框架,反映了 Go 对测试作为核心实践的重视。
理解这些约定是日常必备知识:_test.go 文件和 TestXxx(t *testing.T) 结构、显式(无断言)的失败报告风格,尤其是表驱动测试模式,它在惯用的 Go 中占主导地位(通过子测试的清晰单个 case 报告来紧凑覆盖许多 case)。
Go 的内置基准测试(将性能作为可测试的关切)和强大的工具同样重要——覆盖率分析,特别是**-race 检测器**,它在并发代码中查找数据竞争(鉴于 Go 的并发密集使用至关重要)。
知道如何编写高效的、习惯用法的 Go 测试,使用竞争检测器,以及利用 httptest/接口来测试真实组件,是专业 Go 开发的标志,也是一个反映代码质量理解的常见话题。