Golang:使用init()函数进行测试

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)
}

Your Go test function should be of independent and test one functionality. But in this case, it depends on some other method which is not really good way of testing. And init() is some thing which will get loaded as first step in code execution and I don't think using init in test method is really correct way of doing this.

Less than ideal, but this works for me. Inside of the package that you're testing:

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
    }
    //...
}