在Golang中从测试文件设置变量

10

我尝试从我的单元测试文件中设置一个变量

main_test.go

var testingMode bool = true

main.go

if testingMode == true {
  //use test database
} else {
  //use regular database
}
如果我运行"go test",这将正常工作。如果我运行"go build",golang会抱怨testingMode未定义(因为测试不是程序的一部分)。
但是,如果我在main.go中设置全局变量,则无法在main_test中设置它。
正确的做法是什么?

你在main_test.go文件中的哪里定义了这个变量?记住,你的init()函数在启动时执行,但main()函数不会。 - Pierre Prinetti
我将其定义在测试文件中的任何函数之外。 - Allen
2
可能是重复的问题:在Go中,如何在运行时获取测试环境? - Ainar-G
顺便说一句,这是一种不好的处理测试桩的方式。标准做法是让相关的代码使用一个接口(或在这种情况下可能是一个*sql.DB变量),测试代码可以用模拟实现(或内存中的*sql.DB)来替换它。 - Dave C
有趣。你能指向一个更多关于这个的信息链接吗? - Allen
2个回答

18

尝试这个:

main.go 中将您的变量定义为全局变量:

var testingMode bool

然后在你的测试文件main_test.go中将其设置为true :

func init() {
    testingMode = true
}

我希望在常规执行时测试为false,只有在运行“go test”时才希望测试为true。 - Allen
1
通过这个新的示例,testingMode 将默认为 false(golang 的零值),并且会在 main_test.go 的 init 函数中设置为 true。 - Pierre Prinetti

1

Pierre Prinetti的答案在2019年无效。

相反,做这个。虽然不是最理想的方法,但能完成任务。

//In the module that you are testing (not your test module:
func init() {
    if len(os.Args) > 1 && os.Args[1][:5] == "-test" {
        log.Println("testing")//special test setup goes goes here
        return // ...or just skip the setup entirely
    }
    //...
}

1
有没有一种方法可以在一个特定的单元测试中覆盖一个变量? - Anum Sheraz
有没有其他更简洁的方法来做这件事? - vp8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接