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

5
我有以下的TestMain函数:
func TestMain(m *testing.M) {
  db := "[working_db_connection]"
  dbInstance, _ := InitializeRepo(db, 2)
  runTests := m.Run()
  os.Exit(runTests)
}

以下是样例测试。
func TestSomeFeature(t *testing.T) {
  fmt.Println(dbInstance)
}

函数TestSomeFeature确实运行了,但是说dbInstance未定义。为什么它无法访问该变量?从我看到的示例中,使用此语法访问在TestMain中设置的变量。
2个回答

12

dbInstanceTestMain的局部变量,不存在于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)
}

如果我们这样做,DbInstance 是否会作为包的一部分被导出? - kovac
是的,如果您关心变量导出,您必须将变量名称更改为dbInstance。 - Tinwor

4
你应该在任何函数外定义变量。
var dbInstance DbType

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接