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

编写 Go 语言的单元测试非常简单,标准库中的
testing
假设我们有一个计算两个整数之和的函数,放在
math.go
// math.go
package main
func Add(a, b int) int {
return a + b
}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
在项目目录下执行:
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
对于多个输入组合,推荐使用“表驱动测试”(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)
PASSxxx_test.go
func TestXxx(t *testing.T)
t.Error
t.Fatal
t.Run
基本上就这些。Go 的测试机制简洁直接,配合
go test
以上就是如何编写基础Golang单元测试 使用testing包简单示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号