下面是关于 测试与调试:go test
工具用法 的详解,重点介绍 go test
常用参数、调试技巧、性能测试命令及其在实际项目中的应用。
go test
是 Go 提供的内建测试命令,用于运行单元测试、基准测试、示例测试,并支持测试覆盖率与竞态检测等功能。
一、基本用法
go test # 执行当前包下的所有测试文件
go test -v # 显示详细日志
文件要求:
-
文件名:必须以
_test.go
结尾 -
函数命名:
- 单元测试:
TestXxx(t *testing.T)
- 基准测试:
BenchmarkXxx(b *testing.B)
- 示例测试:
ExampleXxx()
- 单元测试:
二、常用参数说明
参数 | 说明 |
---|---|
-v |
显示每个测试用例的详细执行过程 |
-run regexp |
仅运行函数名匹配的测试(如 go test -run=Add ) |
-bench regexp |
运行匹配的基准测试函数(如 go test -bench=. ) |
-benchmem |
输出内存分配统计信息(搭配 -bench ) |
-count=n |
重复运行测试若干次,可用于发现偶现问题 |
-cover |
输出测试覆盖率 |
-coverprofile=cover.out |
将覆盖率结果写入文件 |
-race |
检测数据竞争 |
-timeout |
设置测试超时时间(默认 10 分钟) |
-short |
在测试中用 testing.Short() 控制长时间用例是否跳过 |
-parallel=n |
设置并发执行测试的最大 goroutine 数 |
三、典型用法示例
1. 指定测试函数运行
go test -run='TestAdd' # 只运行 TestAdd 测试函数
支持正则:
go test -run='Test.*'
2. 基准测试 + 内存分析
go test -bench=. -benchmem
输出示例:
BenchmarkAdd-8 50000000 32.0 ns/op 0 B/op 0 allocs/op
3. 覆盖率测试
go test -cover
go test -coverprofile=cover.out
go tool cover -html=cover.out
4. 检测数据竞争(多线程并发错误)
go test -race
若存在竞争,会输出类似:
WARNING: DATA RACE
Read at 0x00c0000a20b0 by goroutine 6:
5. 设置执行次数与稳定性验证
go test -count=5 -run=TestFlaky
四、测试组织结构推荐
单个包的测试:
math/
├── math.go
└── math_test.go
跨包测试(黑盒):
package mypkg_test // 注意使用 "_test" 后缀
这样可防止访问未导出的内容,模拟真实使用方式。
五、实用技巧汇总
技巧 | 示例 |
---|---|
跳过长测试 | if testing.Short() { t.Skip("skip in short mode") } |
子测试(Subtest) | t.Run("Case1", func(t *testing.T){...}) |
并行测试 | t.Parallel() |
临时文件与清理 | 使用 t.TempDir() 创建自动清理的临时目录 |
六、推荐组合命令(CI常用)
go fmt ./...
go vet ./...
go test -race -cover -v ./...
七、总结一览
功能 | 命令示例 |
---|---|
普通测试 | go test |
显示详情 | go test -v |
跑部分测试 | go test -run=TestXxx |
基准测试 | go test -bench=. |
内存分配 | go test -bench=. -benchmem |
并发检测 | go test -race |
覆盖率报告 | go test -cover , -coverprofile |
可视化覆盖率 | go tool cover -html=cover.out |
统计稳定性 | go test -count=10 -run=TestXxx |
如你有具体场景(如测试数据库、模拟网络等)或对 Mock、Testify 等第三方库感兴趣,也欢迎继续深入探讨!