Setting a variable from a test file in golang

I am trying to set a variable from my unit test 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" it works fine. If I do "go build", golang complains that testMode is not defined (which should be the case since tests are not part of the program).

But it seems that if I set a global variable in main.go, I cannot set it in main_test.

What's the correct way?

+3


source to share


1 answer


Try the following:

Define your variable as global in main.go

:

var testingMode bool

      



And then install it true

in your test file main_test.go

:

func init() {
    testingMode = true
}

      

+5


source







All Articles