【发布时间】:2018-10-12 11:34:24
【问题描述】:
经过阅读,我想我需要这个TestMain(m *testing.M) 构造来设置我的数据库。然而,在运行测试时,db 总是 nil。我该如何解决这个问题?
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")
}
}
输出是:
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 是完整代码的链接。
【问题讨论】: