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?
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
}
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
}
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With