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

huangapple go评论74阅读模式
英文:

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

问题

我有以下的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中设置的变量。

英文:

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.

答案1

得分: 11

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 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)
}

答案2

得分: 4

你应该将变量定义在任何函数之外。

var dbInstance DbType
英文:

You should have your variable defined outside of any function.

var dbInstance DbType

huangapple
  • 本文由 发表于 2017年2月22日 23:38:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/42395897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定