英文:
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
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)
}
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论