高级阶段

测试策略与基准测试

Go 的 testing 包内置了断言、benchmark、fuzz 和覆盖率工具。配合表驱动测试、接口打桩和依赖注入,能覆盖从单元到集成的大部分场景。

最小测试#

go
func TestAdd(t *testing.T) {
	got := Add(1, 2)
	if got != 3 {
		t.Errorf("Add(1, 2) = %d, want 3", got)
	}
}

go test ./... 运行测试,go test -v 显示详细输出。

断言辅助#

go
func TestAdd(t *testing.T) {
	got := Add(1, 2)
	if got != 3 {
		t.Fatalf("Add(1, 2) = %d, want 3", got)  // Fatal 停止当前测试
	}
}

t.Fatal vs t.Error:

  • t.Fatal —— 记录失败并立即终止当前测试函数
  • t.Error —— 记录失败,继续执行后续断言

需要继续执行用 Error,需要停止(比如后续断言会 panic)用 Fatal。

子测试#

go
func TestParse(t *testing.T) {
	cases := []struct {
		name    string
		input   string
		want    int
		wantErr bool
	}{
		{"正数", "42", 42, false},
		{"负数", "-1", -1, false},
		{"零", "0", 0, false},
		{"非法", "abc", 0, true},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			got, err := Parse(tc.input)
			if tc.wantErr {
				if err == nil {
					t.Fatalf("期望出错,但得到了 %d", got)
				}
				return
			}
			if err != nil {
				t.Fatalf("不该出错: %v", err)
			}
			if got != tc.want {
				t.Errorf("Parse(%q) = %d, want %d", tc.input, got, tc.want)
			}
		})
	}
}

表驱动测试#

上面就是表驱动测试。它是 Go 社区的主流写法,优点:

  • 测试数据和逻辑分离,一眼能看出覆盖了哪些场景
  • 容易加边界用例
  • 失败时 t.Run 的子测试名会出现在输出里,定位方便

用 t.Run 的并行测试#

go
for _, tc := range cases {
	tc := tc // Go 1.22 之前必须
	t.Run(tc.name, func(t *testing.T) {
		t.Parallel()  // 并行运行这个子测试
		// ...
	})
}

测试准备与清理#

go
func TestWithTempFile(t *testing.T) {
	dir := t.TempDir()   // 自动清理
	path := filepath.Join(dir, "test.txt")
	// ...
}

func TestWithDB(t *testing.T) {
	db := setupDB(t)
	t.Cleanup(func() {
		db.Close()   // 测试结束后自动执行
	})
	// ...
}

t.Cleanup 是替代 defer 的更好选择——它保证即使 t.Fatal 也会执行(t.Fatal 调用的是 runtime.Goexit,普通 defer 也会执行,但 Cleanup 更语义化,且可以在多个层级注册)。

Mock 与依赖注入#

Go 没有内置 mock 框架,但也没必要——用接口就能手写:

go
type UserRepository interface {
	FindByID(ctx context.Context, id int64) (*User, error)
	Save(ctx context.Context, u *User) error
}

type mockRepo struct {
	users map[int64]*User
	err   error
}

func (m *mockRepo) FindByID(ctx context.Context, id int64) (*User, error) {
	if m.err != nil {
		return nil, m.err
	}
	u, ok := m.users[id]
	if !ok {
		return nil, ErrNotFound
	}
	return u, nil
}

函数式 mock#

对于只有一个方法的接口,用函数类型更简洁:

go
type UserRepository interface {
	FindByID(ctx context.Context, id int64) (*User, error)
}

type repoFunc func(ctx context.Context, id int64) (*User, error)

func (f repoFunc) FindByID(ctx context.Context, id int64) (*User, error) {
	return f(ctx, id)
}

// 使用
repo := repoFunc(func(ctx context.Context, id int64) (*User, error) {
	return &User{ID: id, Name: "mock"}, nil
})

gomock / testify mock#

需要复杂断言和自动生成 mock 时:

go
// 使用 testify
require.NoError(t, err)
assert.Equal(t, 42, got)
assert.ErrorContains(t, err, "timeout")
bash
go install github.com/go-logr/mockgen@latest
mockgen -source=repo.go -destination=repo_mock.go

集成测试#

用 //go:build integration 标签隔离:

go
//go:build integration

package store_test

func TestPostgresStore(t *testing.T) {
	// 真实数据库
}
bash
go test -tags=integration ./...

测试容器#

用 Docker 启动依赖:

go
func TestMain(m *testing.M) {
	// 启动容器
	container, err := postgres.Run(ctx, "postgres:16-alpine", ...)
	// ...
	code := m.Run()
	// 清理
	os.Exit(code)
}

跳过测试#

go
func TestRequiresGPU(t *testing.T) {
	if testing.Short() {
		t.Skip("短测试模式跳过")
	}
	// ...
}
bash
go test -short ./...

覆盖率#

bash
go test -cover ./...
go test -coverprofile=cover.out ./...
go tool cover -html=cover.out    # 生成 HTML 报告

查看函数级别的覆盖:

bash
go tool cover -func=cover.out
✦ 覆盖率不是目标

100% 覆盖率不代表没有 bug。关键是核心路径和错误路径被覆盖。追求覆盖率数字容易写出没有断言的「空测试」。

go
// 反例:没有任何断言的测试
func TestUser(t *testing.T) {
	u := NewUser("Tom")
	_ = u
}

模糊测试#

Go 1.18 引入原生 fuzz:

go
func FuzzParse(f *testing.F) {
	f.Add("42")      // 种子输入
	f.Add("-1")

	f.Fuzz(func(t *testing.T, s string) {
		n, err := Parse(s)
		if err != nil {
			return  // 解析失败是合法的
		}
		// 不变量:解析成功的数字,字符串化后应该能被再次解析且值相等
		got, err := Parse(strconv.Itoa(n))
		if err != nil {
			t.Fatalf("往返失败: %v", err)
		}
		if got != n {
			t.Fatalf("往返值不一致: %d != %d", got, n)
		}
	})
}
bash
go test -fuzz=FuzzParse -fuzztime=30s

fuzz 会把失败的输入保存到 testdata/fuzz/FuzzParse/<hash>,下次普通 go test 会重放。这些文件要提交到 git。

模糊测试适合找:

  • panic
  • 整数溢出
  • 编码解码不往返
  • 边界条件错误

基准测试#

见 pprof 篇。要点回顾:

go
func BenchmarkX(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		// ...
	}
}
bash
go test -bench=. -benchmem -run=^$ ./...

-run=^$ 表示不跑普通测试,只跑 benchmark(跳过它可以省时间)。

测试的组织#

text
pkg/
├── user.go
├── user_test.go        # 单元测试
├── user_integration_test.go
├── user_bench_test.go
└── testdata/
    └── golden.json     # 测试数据

同一包内的测试文件可以访问未导出标识符;_test 后缀的包(package foo_test)只能访问导出标识符。

推荐:核心逻辑用内部测试(package foo),验证公开 API 用外部测试(package foo_test)。

Golden 文件测试#

go
func TestRender(t *testing.T) {
	got := Render(input)

	golden, err := os.ReadFile("testdata/render.golden")
	if err != nil {
		t.Fatal(err)
	}
	if got != string(golden) {
		t.Errorf("输出不匹配:\n--- got ---\n%s\n--- want ---\n%s", got, golden)
	}
}
bash
go test -run=TestRender -update   # 自定义 flag 更新 golden

测试辅助函数#

go
func assertNoError(t *testing.T, err error) {
	t.Helper()   // 重要:报错时定位到调用者而不是这一行
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}

t.Helper() 是关键,否则失败信息总是指向辅助函数内部。

常见问题#

测试之间互相影响#

go
var globalCounter int

func TestA(t *testing.T) { globalCounter++ }
func TestB(t *testing.T) { if globalCounter != 0 { t.Fatal("被污染了") } }

测试可能以任意顺序执行,共享全局状态是隐患。让测试自己创建自己的数据。

时间相关测试不稳定#

go
func TestTimeout(t *testing.T) {
	start := time.Now()
	DoWork()
	if time.Since(start) > 100*time.Millisecond {  // 容易 flaky
		t.Fatal("超时")
	}
}

改进:注入时钟,或者放宽阈值并允许重试。

goroutine 泄漏检测#

go
func TestNoLeak(t *testing.T) {
	before := runtime.NumGoroutine()
	DoWork()
	time.Sleep(100 * time.Millisecond)
	if after := runtime.NumGoroutine(); after > before {
		t.Errorf("goroutine 泄漏: %d -> %d", before, after)
	}
}

更专业的用 go.uber.org/goleak:

go
func TestMain(m *testing.M) {
	goleak.VerifyTestMain(m)
}

CI 配置#

yaml
# .github/workflows/test.yml
- name: Test
  run: |
    go test -race -coverprofile=cover.out -covermode=atomic ./...
    go test -bench=. -benchmem -run=^$ ./...

-race 必须进 CI,它能发现 Go 运行时本身发现不了的数据竞争。

小结#

  • 表驱动测试是主流写法,子测试名帮助定位
  • t.Helper() 让断言错误定位到调用方
  • 依赖用接口隔离,mock 可以手写
  • 覆盖率是参考不是目标,关注核心路径和错误路径
  • 原生 fuzz 适合找 panic 和不变量破坏,失败样本要提交
  • -race 进 CI;用 benchstat 判断性能变化是否显著