Go 语言 testing 包是官方轻量高效内建测试框架,需将测试函数置于 _test.go 文件、以 Test 开头、接收 testing.T 参数;用 t.Error/t.Fatal 等方法报错,支持 t.Run 子测试和 go test -v/-cover 等实用选项。
Go 语言的 testing 包是官方提供的轻量、高效、内建的测试框架,无需额外依赖。编写单元测试时,只需遵循命名规范(测试函数以 Test 开头、参数为 *testing.T),并用 go test 命令运行即可。
测试函数必须放在以 _test.go 结尾的文件中,且与被测代码在同一包内(或使用 xxx_test 包做白盒/黑盒隔离)。函数签名固定为:
Test 开头,后接大写字母开头的有意义名称(如 TestAdd、TestParseURL)*testing.T
Go 不提供内置断言函数,而是通过 *testing.T 的方法显式控制测试流程:
t.Error(...):记录错误,继续执行后续语句t.Errorf(...):带格式化字符串的错误记录(推荐用于含变量的提示)t.Fatal(...) 和 t.Fatalf(...):记录错误并立即终止当前测试函数panic 或 log.Fatal,它们会绕过测试框架,导致结果不可靠例如验证加法函数:func TestAdd(t *testing.T) {
got := Add(2, 3)
if got != 5 {
t.Errorf("Add(2,3) = %d, want 5", got)
}
}
用 t.Run() 可将一个测试函数拆分为多个逻辑子测试,便于分组、过滤和独立失败定位:
TestAdd/positive_numbers)-run 参数只运行匹配的子测试:go test -run "TestAdd/positive"
示例:func TestAdd(t *testing.T) {
t.Run("positive_numbers", func(t *testing.T) {
if got := Add(2, 3); got != 5 {
t.Errorf("expected 5, got %d", got)
}
})
t.Run("negative_numbers", func(t *testing.T) {
if got := Add(-1, -2); got != -3 {
t.Errorf("expected -3, got %d", got)
}
})
}
go test 是核心命令,配合参数可提升效率和可观测性:
go test:运行当前目录下所有 *_test.go 中的测试go test -v:显示详细输出(包括每个测试函数名和日志)go test -run=^TestAdd$:正则匹配精确测试函数(^ 和 $ 防止子串误匹配)go test -cover:显示测试覆盖率百分比go test -coverprofile=c.out && go tool cover -html=c.out:生成 HTML 覆盖率报告