13 - 测试
Go 内置测试框架:testing 包 + go test 命令。
一、单元测试
1. 基本测试
// math.go
package math
func Add(a, b int) int { return a + b }
// math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
got := Add(1, 2)
if got != 3 {
t.Errorf("Add(1, 2) = %d, want 3", got)
}
}
2. 表驱动测试(推荐)
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"正数", 1, 2, 3},
{"零", 0, 0, 0},
{"负数", -1, -2, -3},
{"混合", 10, -5, 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Add(tt.a, tt.b)
if got != tt.want {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
}
})
}
}
3. 子测试
func TestStuff(t *testing.T) {
t.Run("group1", func(t *testing.T) {
t.Run("sub1", func(t *testing.T) { /* ... */ })
t.Run("sub2", func(t *testing.T) { /* ... */ })
})
t.Run("group2", func(t *testing.T) { /* ... */ })
}
// 运行:go test -run TestStuff/group1/sub1
4. 辅助函数
func setupTestDB(t *testing.T) *sql.DB {
t.Helper() // 失败时报告调用者行号
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() }) // 测试结束自动清理
return db
}
func TestQuery(t *testing.T) {
db := setupTestDB(t)
// 使用 db
}
5. 跳过与并行
func TestIntegration(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
// 集成测试
}
func TestParallel(t *testing.T) {
t.Parallel() // 标记可与其他并行
// ...
}
二、常用断言
// t.Errorf - 报告失败,继续执行
if got != want {
t.Errorf("got %v, want %v", got, want)
}
// t.Fatalf - 报告失败,终止当前测试
if err != nil {
t.Fatalf("setup failed: %v", err)
}
// t.Logf - 记录日志(失败时显示)
t.Logf("received %d items", len(items))
// t.Skip - 跳过
t.Skip("TODO: 实现后再启用")
// t.Helper() - 标记 helper,失败报告调用方
三、基准测试
1. 基本基准
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}
go test -bench=BenchmarkAdd -benchmem
# BenchmarkAdd-8 1000000000 0.258 ns/op 0 B/op 0 allocs/op
2. 表驱动基准
func benchmarkAdd(b *testing.B, size int) {
data := make([]int, size)
b.ResetTimer() // 重置计时器,排除 setup
for i := 0; i < b.N; i++ {
for _, v := range data {
_ = Add(v, 1)
}
}
}
func BenchmarkAddSmall(b *testing.B) { benchmarkAdd(b, 10) }
func BenchmarkAddLarge(b *testing.B) { benchmarkAdd(b, 10000) }
3. 并行基准
func BenchmarkConcurrentAdd(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Add(1, 2)
}
})
}
四、测试覆盖率
go test -cover
# ok example.com/app 0.123s coverage: 87.5% of statements
go test -coverprofile=coverage.out
go tool cover -html=coverage.out -o coverage.html
# 打开 coverage.html 查看
五、Mock 与 Stub
// 接口便于 mock
type DB interface {
Get(key string) (string, error)
Put(key, value string) error
}
// 真实实现
type RealDB struct { /* ... */ }
func (r *RealDB) Get(key string) (string, error) { /* ... */ }
// Mock 实现(测试用)
type MockDB struct {
Data map[string]string
}
func (m *MockDB) Get(key string) (string, error) {
v, ok := m.Data[key]
if !ok {
return "", errors.New("not found")
}
return v, nil
}
func (m *MockDB) Put(key, value string) error {
m.Data[key] = value
return nil
}
// 测试
func TestCache(t *testing.T) {
mock := &MockDB{Data: make(map[string]string)}
cache := NewCache(mock)
cache.Put("key", "value")
got, err := cache.Get("key")
if err != nil || got != "value" {
t.Errorf("got %q, want %q", got, "value")
}
}
六、go test 常用选项
# 运行所有测试
go test ./...
# 仅当前包
go test
# 详细输出
go test -v
# 运行指定测试
go test -run TestAdd
# 跳过 cache
go test -count=1
# 短模式(跳过集成)
go test -short
# 并行测试
go test -parallel 4
# 超时
go test -timeout 30s
# 失败立即停止
go test -failfast
# 竞态检测
go test -race
七、模糊测试 (Fuzzing)(Go 1.18+)
func FuzzReverse(f *testing.F) {
f.Add("hello") // seed corpus
f.Fuzz(func(t *testing.T, s string) {
rev := Reverse(s)
if Reverse(rev) != s {
t.Errorf("Reverse(Reverse(%q)) != %q", s, s)
}
})
}
go test -fuzz=FuzzReverse
八、testdata 与 golden 文件
myapp/
├── parser_test.go
├── parser.go
└── testdata/
├── input1.txt
└── expected1.txt
func TestParse(t *testing.T) {
input, _ := os.ReadFile("testdata/input1.txt")
expected, _ := os.ReadFile("testdata/expected1.txt")
got := Parse(string(input))
if string(got) != string(expected) {
t.Errorf("got %q, want %q", got, expected)
}
}
九、综合实战:完整测试体系
1. 项目结构
calc/
├── go.mod
├── cmd/
│ └── calc/
│ └── main.go
├── internal/
│ ├── calc/
│ │ ├── eval.go
│ │ └── eval_test.go
│ └── token/
│ ├── token.go
│ └── token_test.go
├── testdata/
│ └── samples.txt
└── Makefile
2. internal/calc/eval.go
package calc
import "errors"
func Eval(expr string) (float64, error) {
if expr == "" {
return 0, errors.New("empty expression")
}
// 简化:解析 "a + b"
// ...
return 42, nil
}
3. internal/calc/eval_test.go
package calc
import "testing"
func TestEval(t *testing.T) {
tests := []struct {
name string
expr string
want float64
wantErr bool
}{
{"valid", "1 + 2", 3, false},
{"empty", "", 0, true},
{"invalid", "abc", 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Eval(tt.expr)
if (err != nil) != tt.wantErr {
t.Errorf("err = %v, wantErr = %v", err, tt.wantErr)
}
if !tt.wantErr && got != tt.want {
t.Errorf("got %v, want %v", got, tt.want)
}
})
}
}
func BenchmarkEval(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _ = Eval("1 + 2")
}
}
4. Makefile
.PHONY: test test-race cover bench
test:
go test ./...
test-race:
go test -race ./...
cover:
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html
bench:
go test -bench=. -benchmem ./...
5. 测试命令
make test # 全部测试
make test-race # 含竞态检测
make cover # 覆盖率 HTML
make bench # 基准测试
# 单独跑某个
go test -v -run TestEval ./internal/calc/
# 看覆盖率
go test -coverprofile=coverage.out ./...
go tool cover -func=coverage.out # 命令行
go tool cover -html=coverage.out # HTML
十、要点速记
- 测试文件命名:
xxx_test.go,包与被测文件相同 - 测试函数:
func TestXxx(t *testing.T) - 表驱动测试:用
testsslice +t.Run子测试 - 基准测试:
func BenchmarkXxx(b *testing.B),循环b.N次 - 覆盖率:
go test -cover/go tool cover -html - Mock 通过接口实现,注入依赖
- t.Helper() 标记 helper,失败报告调用方
- t.Cleanup 注册清理函数
go test -race必跑(竞态检测)go test -short跳过集成测试go test -fuzz=FuzzXxx模糊测试(Go 1.18+)testdata/放测试数据(golden file)