Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: Testing with init() func

Tags:

go

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)
}
like image 403
Shriram Sharma Avatar asked Jul 20 '16 15:07

Shriram Sharma


People also ask

Should we use init in Golang?

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.

How do you test a function in go?

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.

What is INIT in Golang?

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.


1 Answers

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
}
like image 185
tsubus Avatar answered Oct 22 '22 15:10

tsubus