Go中单元测试通过_test.go文件和Test开头函数实现,使用table-driven和子测试提升可维护性与可读性,支持覆盖率分析及性能基准测试。

在Golang中编写单元测试非常直接,得益于标准库 testing 的简洁设计。只要遵循约定的文件命名和函数结构,就能快速为代码添加可靠的测试覆盖。
Go的测试文件必须以 _test.go 结尾,并放在与被测代码相同的包中。测试函数必须以 Test 开头,参数类型为 *testing.T。
示例:
func TestAdd(t *testing.T) { result := Add(2, 3) if result != 5 { t.Errorf("期望 5,实际 %d", result) } }运行测试使用命令:go test 或更详细的 go test -v 查看每一步输出。
立即学习“go语言免费学习笔记(深入)”;
Go推荐使用表驱动方式测试多个用例,避免重复代码。将输入、期望输出组织成切片,在循环中逐一验证。
func TestDivide(t *testing.T) { tests := []struct { a, b float64 want float64 hasError bool }{ {10, 2, 5, false}, {9, 3, 3, false}, {5, 0, 0, true}, // 除零错误 } for _, tt := range tests { got, err := Divide(tt.a, tt.b) if tt.hasError { if err == nil { t.Errorf("期望错误,但未发生") } } else { if err != nil || got != tt.want { t.Errorf("Divide(%f, %f) = %f, %v; 期望 %f", tt.a, tt.b, got, err, tt.want) } } } }这种方式便于扩展用例,也更容易发现边界情况。
使用 t.Run() 创建子测试,每个用例独立标记,输出更清晰,还能单独运行某个子测试。
func TestAddWithSubtests(t *testing.T) { tests := map[string]struct { a, b int want int }{ "正数相加": {2, 3, 5}, "含零": {0, 5, 5}, "负数": {-1, 1, 0}, } for name, tt := range tests { t.Run(name, func(t *testing.T) { if got := Add(tt.a, tt.b); got != tt.want { t.Errorf("期望 %d,实际 %d", tt.want, got) } }) } }可通过 go test -run TestAddWithSubtests/正数相加 运行特定子测试。
Go内置覆盖率统计功能。运行:go test -cover 查看整体覆盖率,或生成详细报告:
go test -coverprofile=coverage.out go tool cover -html=coverage.out性能测试函数以 Benchmark 开头,使用 *testing.B 参数:
func BenchmarkAdd(b *testing.B) { for i := 0; i运行 go test -bench=. 执行所有性能测试。
Go没有内置 mocking 工具,但可通过接口和手动模拟实现解耦。定义依赖接口,测试时传入模拟实现。
type Sender interface { Send(message string) error } type Notifier struct { Sender Sender } func (n *Notifier) Notify(msg string) error { return n.Sender.Send("NOTIFY: " + msg) }测试时:
type mockSender struct { called bool err error } func (m *mockSender) Send(msg string) error { m.called = true return m.err } func TestNotifier(t *testing.T) { mock := &mockSender{err: nil} notifier := &Notifier{Sender: mock} notifier.Notify("hello") if !mock.called { t.Error("期望 Send 被调用") } }对于复杂场景,可使用第三方库如 gomock 或 testify/mock 自动生成模拟对象。
基本上就这些。Go的测试机制简单但强大,重点是写好用例、覆盖边界、保持测试快速独立。以上就是如何在Golang中编写单元测试_Golang单元测试编写方法汇总的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号