登录
首页 >  Golang >  Go问答

对所有测试文件进行一次初始化,并在每个文件的init()函数中使用它

来源:stackoverflow

时间:2024-03-19 15:15:31 176浏览 收藏

对于需要在所有测试文件中的 `init()` 函数中使用的全局初始化,使用 `testmain` 似乎不合适,因为它是在文件 `init()` 之后运行的。为了解决这个问题,可以使用立即调用的函数文字来初始化顶级变量,确保在 `init()` 之前执行初始化逻辑。通过这种方式,可以在所有测试文件中重用全局初始化,并在 `init()` 中访问初始化后的值。

问题内容

我想初始化一个数据库连接,该连接将由 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()
}

输出(注意数据库连接未初始化):

disconnected
=== RUN   TestThatNeedsDBInitializedByInitFunction
--- PASS: TestThatNeedsDBInitializedByInitFunction (0.00s)
PASS
ok      github.com/fakenews/x   0.002s

鉴于我们不能为此使用 testmain,我们如何为所有测试文件全局初始化一些内容,以便我们可以在测试文件的 init() 中使用它?


正确答案


您可以使用立即调用的函数文字来初始化顶级 db 变量。

var db = func() DB {
    // some connection logic that should be executed before init()
    return DB{session: "connected"}
}()

func init() {
    fmt.Println(db.session) // connected
}

https://play.golang.org/p/j1LFy0n1AsG

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《对所有测试文件进行一次初始化,并在每个文件的init()函数中使用它》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>