Reputation: 21
I'm trying to test my http controllers and I use TestMain func to prepare my testing, but before I run all test requests I need to first run TestAuthUserController
test, which creates and authorizes the user. For this I use wrapper func, which helps me to call 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
}
this is my 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)
}
when I run command go test
- it's ok! the TestMain call it successfuly,
But when I'm trying to run some test separately, for example go test -run TestSomeController
it failed, because of TestAuthUserController
doesn't runs in this case.
Upvotes: 2
Views: 1849
Reputation: 3604
func setupTestUserAndAuthorise(){
// create user, authorise
// return User
}
func deleteTestUser(user User){
// delete user and other clean up actions
}
func TestCase1(t *testing.T){
user := setupUserAndAuthorise()
defer deleteTestUser(user)
// use this user in test
}
You can create a function that creates a new user, authorises and returns it. After the test runs, you can call a cleanup function that deletes user etc.
The order of execution of unit tests should not affect the outcome of tests.
Upvotes: 1
Reputation: 337
I've created main.go file and main_test.go for test file. In main_test.go file it contains below code:
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)
}
When you run this command: go test -run TestAuthUserController
//Here is the output:
Testing is running... testCreateUserSuccessBeforeAuthorize
Testing is running... testAuthorizeUserSuccess
PASS
Hope that this is what your expected. :)
Upvotes: 0