Hidden deep within the source code of mgo lies a small and supereasy package called dbtest (formerly known as testserver). At least, that’s what I keep telling myself because I‘ve never come across this package before, even though I’m using mgo for a long time. So to help others so they don’t replicate my own short-sightedness I thought I’d explain here how to use it.

How?

In the example I’ve created a simple http app with 2 handlers. On to get all pages from MongoDB, and one where you can get a specific one based on slug. The list can be requested by the uri “/” and the page by uri “/page?slug=slug”. For example purposes I omitted all other crud actions. I tried to keep the example as clear as possible so I only used std lib packages, except for MGO of course. I’ll skip the handlers and the main because I think they are pretty self explanatory.

I’ve created an init_test.go file which does the main setup for me. This does 2 things.

Wrapping the testsuite

In the init_test.go you’ll see a TestMain func. This is to wrap the testsuite with the functionality of creating and destroying the MongoDB instance and connection. The package needed for this is:

go get gopkg.in/mgo.v2/dbtest

It is really as easy as that. Now you have full MongoDB support…

Inserting the fixtures

As long as I don’t have an insane amount of fixtures to work with I’d like to insert them directly in my TestMain process. This gives me the freedom of keeping al info of the testdata in one place and the ability to select specific data to test against. This I do by creating a map[string]Type (so I can easily select them later) and loop through to insert them.

I also add a reInsertFixtures() func so I can decide per test to reload my fixtures if needed (for instance to make sure a previous test didn’t delete one of these).

The Tests

And now writing the tests is super simple! By using the httptest package from the net/http std lib you’re able to create a recorder and select a specific handler to test from. I’ve included examples in the gist below which contain some happy and not-so-happy path flows which I use usually. Using

page := pages[“ding”]

enables me to easily test a specific set of data in my test for assertion.

This enables us to completely test our entire GO codebase and ensure our clients the validity of the workings of our API’s! The full example is available on my GitHub page of course.