I have a GO project with this project structure (multiple couples of this kind of files in each package).
- api
- userHandler.go
- userHandler_test.go
- database
- user.go
- user_test.go
Inside user.go I have the User struct and the functions to Create/Get/Update a User (I'm using GORM but this is not the issue). In the user_test.go.
I'd like to have the DB cleaned (with all the data removed or in a certain state) for each different file, so I've tried to create 1 suite (using Testify) for each file, then use the SetupSuite function but the behaviour seems not deterministic, and probably I'm doing something wrong.
So my questions are:
- Which is the best way to have a DB connection shared? Using a global variable is the best option?
- Which is the best way to create the tables in the DB once and then init the DB with custom data before each file_test.go is run?
Right now I'm also having a strange bug: running
go test path/package1
go test path/package2
Everything works fine, but if I run (for testing all the packages)
cd path && go test ./...
I have errors that seems not to be deterministic, that's why I'm guessing that the DB connection is not handled properly
If your
api
package depends on yourdatabase
package (which it appears to) then yourapi
package should have a way to provide a database connection pool (e.g. a*sql.DB
) to it.In your tests for the
api
package, you should just pass in an initialised pool (perhaps with the test schema/fixtures pre-populated) that you can use. This can either be a global you initialise ininit()
for theapi
package or asetup()
anddefer teardown()
pattern in each test function.Here's the former (simplest) approach where you just create a shared database and schema for your tests to use.
Some tips:
setup()
function can create a table with a random suffix and insert your test data so that your tests don't use the same test table (and therefore risk conflicting or relying on each other). Capture that table name and dump it in yourdefer teardown()
function.