




Go测试入门只需掌握go test运行规则:测试文件以_test.go结尾、函数名以Test开头、参数为*testing.T;用表驱动测试组织用例,优先使用t.Error等原生方法。
Go测试入门不需要先学完所有语言特性,而是从 go test 能跑通的第一行断言开始——只要你会写函数,就能立刻写测试。
TestXxx 函数名和 *testing.T 开始写起这是唯一强制要求:测试文件必须以 _test.go 结尾,函数名必须是 Test 开头,参数类型固定为 *testing.T。其他任何“规范”(比如是否用 require、是否 mock)都是后续演进,不是起步门槛。
Add(a, b int) int 就行main.go 同目录下直接建 main_test.go 就能跑func TestAdd(t testing.T)(漏了指针符号 *),会报 missing argument for TestAdd: expected *testing.T
table-driven tests)代替一堆 if 判断手动写多个 、
TestAdd2 是反模式。Go 社区默认用切片组织用例,既清晰又易扩展,且失败时能精准定位哪一组输入出错。
func TestAdd(t *testing.T) {
tests := []struct {
a, b, expected int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tt := range tests {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, result, tt.expected)
}
}
}
t.Errorf 都自带行号和上下文,够用subtest(t.Run)——只有当需要独立 setup/teardown 或想折叠日志时才加expected → Expected),否则在子测试中无法被 go test -v 显示go test 和 go test -v
go test 默认静默运行,只输出 PASS 或失败摘要;go test -v 才显示每个 TestXxx 的执行过程和 t.Log/t.Errorf 输出。没有“调试模式”,也不需要配置文件。
go run xxx_test.go ——会报 undefined: testing.M,Go 测试必须走 go test 入口-race 或 -cover ——它们对新手属于干扰项,等你能稳定写出 5 个以上通过测试再开启no buildable Go source files,检查是否把测试函数写在了非 _test.go 文件里,或包声明写成了 package main_test(应为 package main)最容易被忽略的是:Go 测试不依赖任何第三方断言库,t.Error、t.Fatal、t.Log 这三个方法已覆盖 95% 场景。先用熟它们,比研究 testify 或 gomock 实际得多。