【发布时间】:2018-07-09 21:00:03
【问题描述】:
我正在尝试测试我的 http 控制器并使用 TestMain 函数来准备我的测试,但在我运行所有测试请求之前,我需要先运行 TestAuthUserController 测试,它会创建并授权用户。为此,我使用了 wrapper func,它可以帮助我调用 TestAuthUserController:
func TestMain(m *testing.M) {
//some prepearing steps
AuthUserController()//create and authorize user before all other tests
m.Run()
fmt.Println("after all in main")
dbMdm.End()
}
//AuthUserController is a wrapper func to run TestAuthUserController before all other tests in TestMain func
func AuthUserController() func(t *testing.T){
fmt.Println("in wrapper")
return TestAuthUserController
}
这是我的TestAuthUserController:
//TestAuthUserController tests in series creation of new user and his authorization
func TestAuthUserController(t *testing.T) {
t.Run("testCreateUserSuccessBeforeAuthorize", testCreateUserSuccessBeforeAuthorize)
t.Run("testAuthorizeUserSuccess", testAuthorizeUserSuccess)
}
当我运行命令 go test - 没关系! TestMain 调用它成功,
但是当我尝试单独运行一些测试时,例如go test -run TestSomeController 它失败了,因为TestAuthUserController 在这种情况下不会运行。
【问题讨论】:
-
您要求 go 工具仅运行 TestSomeController,现在想知道为什么 TestAuthUserController 不运行?您得到的正是您所订购的。
-
不要使用
TestMain。只需让每个测试直接调用 setup 函数即可。 -
@Peter,我要求运行 TestSomeController,但是我的 TestAuthUserController 必须在 TestMain(m *testing.M) 中调用,并且在所有情况下都运行 TestMain...
-
如果 TestAuthUserController 不是一个测试,而是一些设置代码,不要让它看起来像一个测试。
-
我遇到了同样的问题。还没有解决方案。