jj1111
jj1111

Reputation: 667

golang TestMain() function sets variable that can't be accessed by tests

I've got the following TestMain function:

func TestMain(m *testing.M) {
  db := "[working_db_connection]"
  dbInstance, _ := InitializeRepo(db, 2)
  runTests := m.Run()
  os.Exit(runTests)
}

and the following sample test

func TestSomeFeature(t *testing.T) {
  fmt.Println(dbInstance)
}

The function TestSomeFeature does run, but says dbInstance is undefined. Why would this not have access to the variable? From examples I'm seeing variables et in TestMain are accessed with this syntax.

Upvotes: 5

Views: 9958

Answers (2)

Tinwor
Tinwor

Reputation: 7973

dbInstance is a local variable of TestMain and it doesn't exist in the lifecycle of TestSomeFeature function. and for this reason the test suite says to you that dbInstance is undefined.
Define the variable as global variable outside TestMain and then instantiate the variable in the TestMain

var DbInstance MyVariableRepoType

func TestMain(m *testing.M) {
  db := "[working_db_connection]"
  DbInstance, _ = InitializeRepo(db, 2)
  runTests := m.Run()
  os.Exit(runTests)
}

Upvotes: 12

Grzegorz Żur
Grzegorz Żur

Reputation: 49181

You should have your variable defined outside of any function.

var dbInstance DbType

Upvotes: 4

Related Questions