Hi I am new to Go and I am writing a simple app which gets some configuration from the env variables. I do this in the init function as shown below.
type envVars struct {
Host string `env:"APP_HOST"`
Username string `env:"APP_USERNAME"`
Password string `env:"APP_PASSWORD"`
}
var envConfig envVars
func init() {
if err := env.Parse(&envConfig); err != nil {
log.Fatal(err)
}
}
I wrote test to verify of the env variables are being read correctly. But the problem is that my program's init func gets called even before my test's init func. Is there any way I can do some sort of setup before my program's init func gets called.
func init() {
os.Setenv("APP_HOST", "http://localhost:9999")
os.Setenv("APP_USERNAME", "john")
os.Setenv("APP_PASSWORD", "doe")
}
func TestEnvConfig(t *testing.T) {
assert.NotNil(t, envConfig)
assert.Equal(t, "http://localhost:9999", envConfig.Host)
}
Golang init() In Go, init() is a very special function meant to execute prior to the main() function. Unlike main(), there can be more than one init() function in a single or multiple files.
At the command line in the greetings directory, run the go test command to execute the test. The go test command executes test functions (whose names begin with Test ) in test files (whose names end with _test.go). You can add the -v flag to get verbose output that lists all of the tests and their results.
The main purpose of the init() function is to initialize the global variables that cannot be initialized in the global context. Example: // Go program to illustrate the. // concept of init() function. // Declaration of the main package.
You can use the TestMain func to control what happens before and after your tests.
For example:
func TestMain(m *testing.M) {
// Write code here to run before tests
// Run tests
exitVal := m.Run()
// Write code here to run after tests
// Exit with exit value from tests
os.Exit(exitVal)
}
func TestYourFunc(t *testing.T) {
// Test code
}
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