Reputation: 63
I have a Go application where application reads environment variables when booting up. The application configures itself using the values of the environment variables.
Now, depending on one of the env variable's value, application gets setup differently than other value of same env variable.
I want to test both these setups in my unit tests. I also want to run these tests in parallel.
I can set env variable value using os.Setenv()
in one test but that will also impact another test running in parallel that tries to set a different value for this same env variable.
What is the best practice in such cases? And how can we set env variables values that do not impact across unit tests.
Upvotes: 2
Views: 1954
Reputation: 79604
Don't use environment variables in your testing. Instead, pass the configuration into your tested function. During normal start up, read that configuration from the environment, but during testing, pass it in directly. Example:
Your code:
func main() {
envFoo := os.Getenv("FOO")
if err := someFunc(envFoo); err != nil {
log.Fatal(err)
}
}
func someFunc(confValue string) error {
// do stuff
}
Your test:
func TestSomeFunc(t *testing.T) {
err := someFunc("test config value")
// assert things
}
Upvotes: 1