go代码测试综合指南(三)
Testing 软件包
testing
软件包在 Go 测试中发挥着关键作用。 它让开发者能够使用不同类型的测试函数创建单元测试。
testing.T
类型提供了控制测试执行的方法,例如使用
Parallel()
并行运行测试,使用
Skip()
跳过测试,以及使用
Cleanup()
调用测试拆解函数。
错误和日志
testing.T
类型提供了多种与测试工作流交互的实用工具,包括
t.Errorf()
,它会输出错误消息并将测试设为失败。
务必需要注意的是,
t.Error*
不会停止测试的执行。 测试完成后,所有遇到的错误都将被报告。 有时,执行失败更有意义,在这种情况下,您应该使用
t.Fatal*
。 测试执行期间,使用
Log*()
函数输出信息可能会很方便:
1 | ``` |
func TestFooerParallel(t *testing.T) {
t.Run(“Test 3 in Parallel”, func(t *testing.T) {
t.Parallel()
result := Fooer(3)
if result != “Foo” {
t.Errorf(“Result was incorrect, got: %s, want: %s.”, result, “Foo”)
}
})
t.Run(“Test 7 in Parallel”, func(t *testing.T) {
t.Parallel()
result := Fooer(7)
if result != “7” {
t.Errorf(“Result was incorrect, got: %s, want: %s.”, result, “7”)
}
})
}
1 |
|
func TestFooerSkiped(t *testing.T) {
if testing.Short() {
t.Skip(“skipping test in short mode.”)
}
result := Fooer(3)
if result != “Foo” {
t.Errorf(“Result was incorrect, got: %s, want: %s.”, result, “Foo”)
}
}
1 |
|
func Test_With_Cleanup(t *testing.T) {
// Some test code
defer cleanup()
// More test code
}
1 |
|
func Test_With_Cleanup(t *testing.T) {
// Some test code here
t.Cleanup(func() {
// cleanup logic
})
// more test code here
}
1 |
|
func helper(t *testing.T) {
t.Helper()
// do something
}
func Test_With_Cleanup(t *testing.T) {
// Some test code here
helper(t)
// more test code here
}
1 |
|
func TestFooerTempDir(t *testing.T) {
tmpDir := t.TempDir()
// your tests
}
这个函数非常实用,但由于相对较新,许多 Go 开发者尚未了解,仍在测试中手动管理临时目录。