t.Run用于创建子测试,每个子测试独立运行并报告结果。通过表驱动测试结合t.Run可提升测试可读性和维护性,支持并行执行(t.Parallel)、条件跳过或终止(t.Skip/t.Fatal)。子测试名称应清晰描述场景,可用嵌套结构组织逻辑,如测试不同HTTP路由。合理使用t.Run能使测试更模块化、便于定位问题。

在Go语言中,使用
t.Run
通过
*testing.T
Run
func TestAdd(t *testing.T) {
tests := map[string]struct {
a, b, expected int
}{
"positive numbers": {1, 2, 3},
"negative numbers": {-1, -2, -3},
"zero values": {0, 0, 0},
}
<pre class='brush:php;toolbar:false;'>for name, tc := range tests {
t.Run(name, func(t *testing.T) {
result := Add(tc.a, tc.b)
if result != tc.expected {
t.Errorf("got %d, want %d", result, tc.expected)
}
})
}}
上述代码中,每个测试用例作为子测试运行。若某个用例失败,其他仍会继续执行,且输出会清晰标明是哪个子测试出错。
立即学习“go语言免费学习笔记(深入)”;
子测试具有独立的生命周期,支持使用
t.Parallel()
t.Parallel()
t.Skip()
t.Fatal()
t.Run("parallel test", func(t *testing.T) {
t.Parallel()
// 模拟耗时测试
time.Sleep(100 * time.Millisecond)
if Add(2, 3) != 5 {
t.Error("expected 5")
}
})
子测试名称应清晰表达测试意图,推荐使用描述性字符串。对于复杂结构,可通过层级嵌套进一步划分逻辑。
例如,在测试API路由时:
t.Run("router", func(t *testing.T) {
r := NewRouter()
t.Run("GET /users", func(t *testing.T) {
req := httptest.NewRequest("GET", "/users", nil)
// 测试逻辑...
})
t.Run("POST /users", func(t *testing.T) {
req := httptest.NewRequest("POST", "/users", nil)
// 测试逻辑...
})
})
基本上就这些。合理使用
t.Run
以上就是Golang使用t.Run实现子测试方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号