Reputation: 1406
I have a test package in go which tests some stuff that depend on reading a configuration. I want to read that configuration once before running all tests so I'm trying to use TestMain(m *testing.M)
:
main.go:
package tests
import (
...
)
var logger = logging.MustGetLogger("tests")
func TestMain(m *testing.M) {
logger.Info("Initializing test suite")
viper.SetConfigName("config")
viper.AddConfigPath("..\\..\\")
err := viper.ReadInConfig()
if err == nil {
os.Exit(m.Run())
} else {
logger.Fatal("Could not read configuration")
}
}
And I have another file in the same directory (and package) with a test.
repository_test.go:
package tests
import (
...
)
func TestCreation(t *testing.T) {
aa := myModule.CreateRepository()
assert.NotNil(t, aa)
}
My problem is that the test fails because the configuration is not read from the file. When I try to debug the test in Gogland a breakpoint inside TestMain
is not hit. When I run the tests from command line I don't see any printouts from TestMain
.
Is there something special I should do to make it work? From what I read online I understood that if I define TestMain(m *testing.M)
then it's going to run just once for the package and that's where I'm supposed to write any setup or teardown code.
Upvotes: 3
Views: 5646
Reputation: 144
TestMain is only executed in test files (suffix _test.go
).
Move the function to the repository_test.go file to fix this.
Upvotes: 12
Reputation: 7477
Make sure that the run configuration is set to Package not File in Run | Edit Configurations... | Go Test | Name of your configuration and this should work. If it doesn't, please post the commands the IDE runs to execute the tests.
Upvotes: 0