【发布时间】:2021-10-04 02:35:00
【问题描述】:
我想在init() 中初始化多个测试文件将使用的数据库连接。
我想只初始化一次数据库连接,然后重用连接,而不是在每个测试文件中初始化init()中的连接。
这似乎是TestMain 的一个用例,但是TestMain 似乎在文件的init() 之后运行(我觉得有点奇怪,因为TestMain 似乎被用来做一些一次性的全局操作测试初始化):
type DB struct {
session string
}
var db = DB{session: "disconnected"}
func TestMain(m *testing.M) {
// We would like to init the DB connection once here, for all of our test files
db = DB{session: "connected"}
exitVal := m.Run()
os.Exit(exitVal)
}
func init() {
// We want to do some initialization with a DB connection here
// We have multiple test files, each with an init, but they should all use the same db
// connection
// Unfortunately, a test file's init() seems to be called _after_ TestMain is called once
// globally
fmt.Println(db.session)
}
func TestThatNeedsDBInitializedByInitFunction(t *testing.T) {
// some test that requires DB initalization in the test file's init()
}
输出(注意DB连接未初始化):
disconnected
=== RUN TestThatNeedsDBInitializedByInitFunction
--- PASS: TestThatNeedsDBInitializedByInitFunction (0.00s)
PASS
ok github.com/fakenews/x 0.002s
鉴于我们不能为此使用TestMain,我们如何以一种可以在测试文件的init() 中使用的方式为所有测试文件全局初始化一次?
【问题讨论】: