go语言单元测试通过testing包实现,测试文件命名为xxx_test.go且与被测文件同包,测试函数以test开头并接收*testing.t参数,使用t.errorf或t.fatalf报告错误,推荐采用表驱动测试方式并通过t.run创建子测试以提高可维护性和可读性,运行go test命令执行测试并用-v参数查看详细结果,最终确保代码正确性。

编写 Go 语言的单元测试非常简单,标准库中的
testing包提供了完整的支持。下面通过一个基础示例,展示如何为一个简单的函数编写单元测试。
1. 被测试函数示例
假设我们有一个计算两个整数之和的函数,放在
math.go文件中:
// math.go
package main
func Add(a, b int) int {
return a + b
}2. 编写对应的测试文件
Go 的测试文件命名规则是:
_test.go,且与被测文件在同一个包中。创建
math_test.go:
立即学习“go语言免费学习笔记(深入)”;
// math_test.go
package main
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("Add(2, 3) = %d; expected %d", result, expected)
}
}说明:
- 测试函数名必须以
Test
开头,可选后接大写字母或单词(如TestAdd
,TestAddNegative
)。 - 参数
t *testing.T
是测试的上下文,用于记录错误、控制测试流程。 - 使用
t.Errorf
报告错误,测试会标记为失败,但继续执行;t.Fatalf
会中断测试。
3. 运行测试
在项目目录下执行:
go test
输出应为:
PASS ok your-project-name 0.001s
如果想看更详细的信息,加上
-v参数:
go test -v
输出类似:
=== RUN TestAdd --- PASS: TestAdd (0.00s) PASS ok your-project-name 0.001s
4. 添加更多测试用例(表驱动测试)
对于多个输入组合,推荐使用“表驱动测试”(table-driven test),更清晰、易维护:
// math_test.go
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -2, -3, -5},
{"mixed signs", -2, 3, 1},
{"zero", 0, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("got %d, want %d", result, tt.expected)
}
})
}
}说明:
- 使用
t.Run
创建子测试,每个测试用例独立运行。 - 输出中会显示每个子测试的名称,便于定位失败项。
运行结果示例:
=== RUN TestAdd
=== RUN TestAdd/positive_numbers
=== RUN TestAdd/negative_numbers
=== RUN TestAdd/mixed_signs
=== RUN TestAdd/zero
--- PASS: TestAdd (0.00s)
--- PASS: TestAdd/positive_numbers (0.00s)
--- PASS: TestAdd/negative_numbers (0.00s)
--- PASS: TestAdd/mixed_signs (0.00s)
--- PASS: TestAdd/zero (0.00s)
PASS小结
- 测试文件命名:
xxx_test.go
- 测试函数:
func TestXxx(t *testing.T)
- 使用
t.Error
或t.Fatal
报告错误 - 推荐使用表驱动测试处理多用例
- 用
t.Run
组织子测试,提升可读性
基本上就这些。Go 的测试机制简洁直接,配合
go test命令即可快速验证代码正确性。










