Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting a variable from test file in golang

Tags:

go

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?

like image 375
Allen Avatar asked May 21 '15 09:05

Allen


2 Answers

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
}
like image 50
Pierre Prinetti Avatar answered Oct 08 '22 20:10

Pierre Prinetti


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
    }
    //...
}
like image 1
VolatileCoder Avatar answered Oct 08 '22 21:10

VolatileCoder