golang TestMain()函数设置测试无法访问的变量

jj1*_*111 0 testing go

我有以下TestMain函数:

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

以及样本测试

func TestSomeFeature(t *testing.T) {
  fmt.Println(dbInstance)
}
Run Code Online (Sandbox Code Playgroud)

函数TestSomeFeature确实运行,但是说dbInstance是未定义的.为什么这不能访问变量?从示例中我可以看到使用此语法访问TestMain中的变量et.

Tin*_*wor 7

dbInstance是一个局部变量,TestMain它在TestSomeFeature函数的生命周期中不存在.由于这个原因,测试套件对你说dbInstance是未定义的.
将变量定义为TestMain外部的全局变量,然后在TestMain中实例化变量

var DbInstance MyVariableRepoType

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