我有以下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.
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)