I am trying to write database integration tests in my go application for my repositories files.
My idea was to leverage the TestMain
function to do the database bootstrap before the tests are run.
Example:
test/integration/integration_test.go
// +build integrationdb
package main
func TestMain(m *testing.M) {
flag.Parse()
// setup database
setupDB()
// run tests
os.Exit(m.Run())
}
Because this is global to all my integration tests I have placed this code in the test/integration package.
Then in each module/package of my application, together with my repository.go code, I have a repository_test.go
with my test code:
// +build integrationdb
package todo_test
import (
"github.com/brpaz/go-api-sample/internal/todo"
"github.com/brpaz/go-api-sample/test/testutil"
"github.com/stretchr/testify/assert"
"testing"
)
func TestPgRepository_CreateTodo(t *testing.T) {
db, err := testutil.GetTestDBConnection()
if err != nil {
t.Fatal(err)
}
repo := todo.NewPgRepository(db)
err = repo.CreateTodo(todo.CreateTodo{
Description: "some-todo",
})
assert.Nil(t, err)
}
The setup works fine, the issue is that when running the tests, it says "testing: warning: no tests to run" and the tests are still executed, without running the TestMain
function.
It seems that the TestMain
function is per package? Is that true? Any workarounds?
I could put all the test files into a unique and separate package (I do that for higher-level tests like acceptance and smoke tests), but since I am testing each repository individually, It doesn't differ that much from a unit test, so I think it makes sense to keep then together with the code.
I guess I could create a TestMain
per package and have some global variable in my global testutils
package that kept if the database was initialized and run the setup if not set. Not really a fan of globals.
The other alternative I see is to move the setup code outside of the test logic. I prefer it to keep tightly integrated with Go as it makes it easier to defer cleanup functions for example, after the tests run.
Maybe I can create my own "integration test runner" command, that would run the setup code and then call "go test" programmatically?
Any other ideas?
Thank you.
Aucun commentaire:
Enregistrer un commentaire