duanleiming2014
2015-05-21 09:30 阅读 23
已采纳

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

i'm trying to set a variable from my unit tests file

main_test.go

var testingMode bool = true

main.go

if testingMode == true {
  //use test database
} else {
  //use regular database
}

If I run "go test", this works fine. If I do "go build", golang complains that testingMode is not defined (which should be the case since tests aren't part of the program).

But it seems if I set the global variable in main.go, I'm unable to set it in main_test.

What's the correct way to about this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dt56449492 dt56449492 2015-05-21 09:42

    Try this:

    Define your variable as global in main.go:

    var testingMode bool
    

    And then set it to be true in your test file main_test.go:

    func init() {
        testingMode = true
    }
    
    点赞 评论 复制链接分享
  • dongpo7467 dongpo7467 2019-09-16 22:08

    Pierre Prinetti's Answer doesn't work in 2019.

    Instead, do this. It's less then ideal, but gets the job done

    //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
        }
        //...
    }
    
    点赞 评论 复制链接分享

相关推荐