Go 测试完整指南 #
基本命令 #
go test # 测试当前包
go test ./... # 递归测试所有子包
go test -v # 详细输出
go test -run TestFunc # 只运行特定测试函数
常用参数详解 #
| 参数 | 说明 | 示例 |
|---|---|---|
-v | 详细输出,显示每个测试函数结果 | go test -v |
-cover | 显示代码覆盖率 | go test -cover |
-coverprofile | 生成覆盖率文件 | go test -coverprofile=coverage.out |
-bench | 运行性能测试 | go test -bench=. |
-benchmem | 显示内存分配统计 | go test -bench=. -benchmem |
-timeout | 设置超时时间 | go test -timeout 30s |
-race | 启用竞态检测 | go test -race |
-short | 跳过耗时的测试 | go test -short |
-tags | 指定构建标签 | go test -tags=integration |
单元测试 vs 集成测试 #
单元测试 #
- 目的: 测试单个函数/方法
- 特征: 快速、隔离、可重复
- 执行: 毫秒级
func TestCalculatePrice(t *testing.T) {
price := CalculatePrice(100, 0.1)
if price != 90.0 {
t.Errorf("Expected 90.0, got %f", price)
}
}
集成测试 #
- 目的: 测试模块间协作
- 特征: 依赖外部系统、测试完整流程
- 执行: 秒级或分钟级
集成测试标注方式 #
方式一:Build Tags(推荐) #
文件顶部添加构建标签:
//go:build integration
// +build integration
package user_test
func TestUserRegistrationIntegration(t *testing.T) {
// 集成测试代码
}
运行命令:
# 只运行集成测试
go test -tags=integration ./...
# 跳过集成测试(单元测试)
go test ./...
方式二:测试内部判断 #
func TestDatabaseIntegration(t *testing.T) {
if testing.Short() {
t.Skip("跳过集成测试在 -short 模式下")
}
// 集成测试代码
}
运行命令:
# 跳过集成测试
go test -short ./...
# 运行所有测试
go test ./...
Makefile 测试任务示例 #
# 标准测试
test:
go test -v -race -coverprofile=coverage.out ./...
# 覆盖率测试
test-coverage:
go test -v -race -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html
# 单元测试(快速)
test-unit:
go test -v -short ./...
# 集成测试
test-integration:
go test -v -tags=integration ./...
# 基准测试
test-bench:
go test -bench=. -benchmem ./...
最佳实践文件结构 #
pkg/
├── user.go
├── user_test.go # 单元测试
├── user_integration_test.go # 集成测试
└── user_bench_test.go # 基准测试
测试函数命名规范 #
- 单元测试:
TestFunctionName - 基准测试:
BenchmarkFunctionName - 示例测试:
ExampleFunctionName
覆盖率报告生成 #
# 生成覆盖率数据
go test -coverprofile=coverage.out ./...
# 查看覆盖率统计
go tool cover -func=coverage.out
# 生成HTML报告
go tool cover -html=coverage.out -o coverage.html
核心哲学 #
Go 测试遵循"约定优于配置"原则:
- 测试文件以
_test.go结尾 - 测试函数以
Test开头 - 简单直接,无需复杂配置
参考文档: Go Testing Package