After some reading, I think I need this TestMain(m *testing.M)
construct to setup my database. However when it comes to running a test, db is always nil. How do I fix this?
var db *sql.DB
func TestMain(m *testing.M) {
db, err := sql.Open("mysql", os.Getenv("DSN"))
if err != nil {
log.Fatal("error opening database")
}
defer db.Close()
log.Printf("here testing with %v", db)
code := m.Run()
log.Printf("finished test")
os.Exit(code)
}
func Test_getRole(t *testing.T) {
if db == nil {
t.Fatalf("db is nil")
}
}
Output is:
2018/05/02 19:10:14 here testing with &{{bugzilla:SECRET@tcp(example.com:3306)/bugzilla?multiStatements=true 0x7aba40} 0 {0 0} [] map[] 0 0 0xc42001e180 0xc4200740c0 false map[] map[] 0 0 0 <nil> 0x4e9850}
--- FAIL: Test_getRole (0.00s)
main_test.go:32: db is nil
https://github.com/unee-t/processInvitations/blob/testfail/main_test.go#L43 is a link to the full piece of code.
Your line db, err := sql.Open("mysql", os.Getenv("DSN"))
creates a local variable db (local to function TestMain). Instead use:
err := nil
db, err = sql.Open("mysql", os.Getenv("DSN"))