Dyna Rizki Habibah
Dyna Rizki Habibah

Reputation: 141

Function TestMain didn't run

Seems like my func TestMain didn't run

I have 2 file in my test folder /_test. One is /main_test.go, another one is /api_city_find_all_test.go.

I run the second one and there's panic error says that i got nil pointer i tried printout something in my /main_test.go in func TestMain but it didn't print anything, seems like the main_test.go didn't work/run

anyone can help me with this?

main_test.go

func TestMain(m *testing.M) {

  fmt.Print("TEST@@")

  os.Chdir("../../../")

  boot.Bootstrap()

  rajaongkir.Register()

  os.Exit(m.Run())
}

I run
api_city_find_all_test.go

func TestApiCityFindAllTest(t *testing.T) {
  goreq := libraries.Request("http://localhost:8181").Post([]string{"rajaongkir/city/findAll"}, nil, `{}`)

  req, _ := goreq.MakeRequest()
  resp := httptest.NewRecorder()

  fmt.Print("TEST!!")

  utilities.Globals.Router.ServeHTTP(resp, req)

  respBody, _ := ioutil.ReadAll(resp.Body)

  t.Log(string(respBody))

  assert.NotEqual(t, "null", string(respBody))
}

I expect the "TEST!!" in api_rajaongkir_city_find_all_test.go and "TEST@@" in main_test.go are printed but just "TEST!!" shown up, it means the main_Test.go didn't run

Upvotes: 2

Views: 827

Answers (1)

tynn
tynn

Reputation: 39853

The TestMain function is local to a test package.

If a test file contains a function:

func TestMain(m *testing.M)

then the generated test will call TestMain(m) instead of running the tests directly.

You have to make sure that both files define the same package or define TestMain(m) in both files.

Upvotes: 3

Related Questions