在同一个包中调用函数和变量,但使用构建标签调用不同的文件

Calling functions and variables in same package but different files with build tags

我正在设置一些集成测试,这是在我的 src 代码的单独测试包中进行的。这样做是为了防止循环依赖。单元测试不存储在这里,它们与正在测试的文件一起存储。

我的 golang 项目层次结构如下:

命令 public ... 测试/ main_test.go database_test.go

在 main_test.go 中,我计划初始化与外部依赖项的连接,例如我的测试数据库。

package tests

type Database struct {
...
}
var DB Database

func TestMain(m *testing.M){
 SetUpDatabase()
 exitCode := m.Run()
 os.Exit(exitCode)
}

database_integration_test.go

func Test(t *testing.T) {

    tests := []struct {
        title string
        run   func(t *testing.T)
    }{
        {"should make query", testQuery},

    }
    for _, test := range tests {
        t.Run(test.title, func(t *testing.T) {
            test.run(t)
        })
    }
}

func testQuery(t *testing.T) {

    var r result.Result
    err := DB.database.DoQuery("").Decode(&r)

    if err != nil {
        t.Errorf(err.Error())
        t.Fatal()
    }
}

此设置在我 运行 时有效,但是,我想向这些文件添加构建标签,或者类型:// +build integration 但是,一旦我使用构建标签,database_integration_test.go 文件就看不到初始化的数据库类型。我怎样才能阻止这个?另外作为旁注,我应该更改 main_test.go 的名称吗?我之所以这样称呼它是因为 main 是标准入口点。

您只需在 TestMain 中添加一个标志即可:

var isIntegration bool

func init() {
    flag.StringVar(&isIntegration, "mytest.integration", "Set flag to set up DB for integration tests")
}

func TestMain(t *testing.M) {
    SetUpDatabase(isIntegration)
    //etc...
}

然后根据参数是 true 还是 false 简单地让 SetUpDatabase 调用不同的、未导出的函数。那将是获得行为的快速方法,而无需过多地了解自定义构建约束。特别是考虑到您是 运行 测试,而不是 构建 应用程序本身。

就重命名 main_test.go 而言:我不明白您为什么需要更改它。它按照锡罐上的说明进行操作。当其他人想要查看测试如何 structured/run,或者添加了哪些可能的标志时,只需检查目录并查找 main_test.go 文件(以及 init.go,那将是我要查找的第一个文件)。任何其他名称,如 setup_integration_test.gointegration_setup_test.gointegration_start_test.go,...只会搅浑水。

首先,关于这一点:

Also as a side note, should I change the name of main_test.go. I only called it that due to main being the standard entry point.

我认为将其命名为 main_test.go 会造成混淆,因为它可能表明您正在测试此文件中的主要功能(根据 golang 约定)

其次,关于这个:

However, as soon as I use the build tag, the database_integration_test.go file cannot see the initialised Database type. How can I stop this?

构建约束或也称为构建标签用于在构建过程中包含或排除包中的文件。有了这个,我们可以从相同的源代码构建不同类型的构建。

因此,如果您没有看到数据库类型被初始化,那么很可能数据库类型的定义和集成测试被标记了不同的构建标签。确保它们存在于相同的构建标签中。另外,我认为您可以使用多个构建标签来标记一个文件。所以你也可以试试。

有关构建标签的更多详细信息,请查看 Dave Cheney 的以下文章 here