题目
编写一个简单的Go测试函数
信息
- 类型:问答
- 难度:⭐
考点
Go测试基础,测试函数命名,测试断言
快速回答
在Go中编写测试需要:
- 创建
_test.go后缀的文件 - 导入
testing包 - 测试函数命名格式:
TestXxx(t *testing.T) - 使用
t.Error或t.Fatal报告失败 - 运行测试:
go test
1. 原理说明
Go内置的testing包提供轻量级测试框架:
- 测试文件必须命名为
*_test.go - 测试函数必须是
TestXxx格式(Xxx首字母大写) - 测试函数参数固定为
t *testing.T - 通过
t的方法控制测试流程和报告
2. 代码示例
被测代码(math.go):
package math
func Add(a, b int) int {
return a + b
}测试代码(math_test.go):
package math
import "testing"
func TestAdd_PositiveNumbers(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("预期 %d, 实际 %d", expected, result)
}
}
func TestAdd_NegativeNumbers(t *testing.T) {
if Add(-1, -1) != -2 {
t.Fatal("负数加法失败") // 立即终止当前测试
}
}3. 最佳实践
- 命名规范:
Test[功能]_[场景](如TestAdd_Overflow) - 错误报告:
t.Error:报告失败但继续执行t.Fatal:严重错误时立即终止
- 表格驱动测试:推荐使用循环测试多组数据
4. 常见错误
- ❌ 测试函数名不以
Test开头 - ❌ 忘记导入
testing包 - ❌ 测试函数签名错误(如缺少
t *testing.T) - ❌ 在测试函数中使用
panic代替错误报告
5. 运行与输出
执行测试:
go test -v # -v 显示详细输出成功输出:
=== RUN TestAdd_PositiveNumbers
--- PASS: TestAdd_PositiveNumbers (0.00s)
=== RUN TestAdd_NegativeNumbers
--- PASS: TestAdd_NegativeNumbers (0.00s)
PASS失败输出(示例):
=== RUN TestAdd_PositiveNumbers
math_test.go:10: 预期 5, 实际 6
--- FAIL: TestAdd_PositiveNumbers (0.00s)6. 扩展知识
- 子测试:使用
t.Run()创建嵌套测试 - 覆盖率:
go test -cover查看测试覆盖率 - 基准测试:
BenchmarkXxx(b *testing.B)函数