unit-testing - 使用 std 测试包对每个测试进行设置和拆卸

标签 unit-testing go

我正在使用“测试”包。像下面这样运行我的测试。

func TestMain(m *testing.M) {

   ...
   // Setup
   os.Exit(m.Run())
   // Teardown
}

这将在运行任何测试之前运行设置,并在所有测试完成后进行拆卸。我确实需要这个,因为设置会设置数据库。而且,我需要,但还没有找到一种方法来运行每个测试设置/拆卸。对于我正在运行的单元测试,我想在每次测试之前清除 DB,这样 DB 的内容就不会出现导致意外行为的问题。

最佳答案

Update for Go 1.14 (2020 年第一季度)

testing 包现在支持清理函数,在测试或基准测试完成后调用,通过调用 T.CleanupB.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/

相关文章:

c - Valgrind 使用 g_test_trap_subprocess () 给出可能丢失的内存

javascript - 我什么时候应该在我的 Angular JS 单元测试中使用 $provide 与 Jasmine Spies

c# - 使用 Moq 模拟 'new()' 约束

pointers - 在 Go-lang 中返回对结构的引用

go - 在 golang 中创建一段缓冲 channel

shell - 这个论点是如何扩大的?

regex - Golang 正则表达式从 git url 中解析出 repo 名称

python - 如何使用 Django Rest Framework 对 HTTP 删除进行单元测试

c# - 单元测试预期在 MSTest 上调用异步操作时抛出异常

go - 在 Golang 中创建数组文字数组