【问题标题】:Initialise something once for all test files, and use it in their init()为所有测试文件初始化一次,并在它们的 init() 中使用它
【发布时间】: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() 中使用的方式为所有测试文件全局初始化一次?

【问题讨论】:

    标签: go testing


    【解决方案1】:

    您可以使用立即调用的函数字面量来初始化顶级 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

    【讨论】:

    • 您的任何测试都会并行运行吗?如果是这样,您是否使用了线程安全的数据库访问库?
    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2020-08-23
    • 2018-08-12
    • 1970-01-01
    相关资源
    最近更新 更多