我正在使用“测试”包。像下面这样运行我的测试。
func TestMain(m *testing.M) {
...
// Setup
os.Exit(m.Run())
// Teardown
}
这将在运行任何测试之前运行设置,并在所有测试完成后进行拆卸。我确实需要这个,因为设置会设置数据库。而且,我需要,但还没有找到一种方法来运行每个测试设置/拆卸。对于我正在运行的单元测试,我想在每次测试之前清除 DB,这样 DB 的内容就不会出现导致意外行为的问题。
最佳答案
Update for Go 1.14 (2020 年第一季度)
testing
包现在支持清理函数,在测试或基准测试完成后调用,通过调用 T.Cleanup
或 B.Cleanup
分别。例如,
func TestFunction(t *testing.T) {
// setup code
// sub-tests
t.Run()
t.Run()
...
// cleanup
t.Cleanup(func(){
//tear-down code
})
}
这里,t.Cleanup 在测试之后运行,它的所有子测试都完成了。
原始答案(2017 年 2 月)
如 Go unit test setup and teardown 的文章“Kare Nuorteva”所示,你可以使用一个设置函数,它返回......一个拆解函数给你 defer。
见 this gist :
func setupSubTest(t *testing.T) func(t *testing.T) {
t.Log("setup sub test")
return func(t *testing.T) {
t.Log("teardown sub test")
}
}
setup 函数负责定义和返回拆解函数。
对于每个测试,例如在表驱动的测试场景中:
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
teardownSubTest := setupSubTest(t)
defer teardownSubTest(t)
result := Sum(tc.a, tc.b)
if result != tc.expected {
t.Fatalf("expected sum %v, but got %v", tc.expected, result)
}
})
}
关于unit-testing - 使用 std 测试包对每个测试进行设置和拆卸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310088/