我正在尝试测试我的http控制器,我使用TestMain func来准备我的测试,但在运行所有测试请求之前,我需要先运行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
在这种情况下不会运行。
答案 0 :(得分:0)
我为测试文件创建了main.go文件和main_test.go。在main_test.go文件中,它包含以下代码:
func TestMain(m *testing.T) {
fmt.Println("Testing is running...")
AuthUserController()
}
func AuthUserController() func(t *testing.T){
fmt.Println("in wrapper")
return TestAuthUserController
}
func testCreateUserSuccessBeforeAuthorize(m *testing.T) {
fmt.Println("create user... testCreateUserSuccessBeforeAuthorize")
}
func testAuthorizeUserSuccess(m *testing.T) {
fmt.Println("authorize user... testAuthorizeUserSuccess")
}
func TestAuthUserController(t *testing.T) {
t.Run("testCreateUserSuccessBeforeAuthorize", testCreateUserSuccessBeforeAuthorize)
t.Run("testAuthorizeUserSuccess", testAuthorizeUserSuccess)
}
运行此命令时: go test -run TestAuthUserController
//Here is the output:
Testing is running... testCreateUserSuccessBeforeAuthorize
Testing is running... testAuthorizeUserSuccess
PASS
希望这是你的预期。 :)
答案 1 :(得分:0)
x
您可以创建一个函数,该函数创建一个新用户,对其进行授权并返回。 测试运行后,您可以调用清除功能,以删除用户等。
单元测试的执行顺序不应影响测试结果。