One thing has always bothered me while writing tests is the lack of a real datasource to run tests against. Most projects I’ve worked with in the past have either mocked responses from a datastore or used a “common” datastore to perform tests against. While mocks are good for quick unit tests, I still prefer using a “real” datasource, especially for integration tests.
While taking Bill Kennedy’s Ultimate Go training a while ago, I saw Bill recommend a testing approach which involved “spinning up” a database container right from within your test code, run your tests, and clean-up. See this for reference. I love this approach. It provides a wonderful way to do everything from within go test without meddling with external scripts, thereby providing much greater interoperability. My only gripe with this is the fact that it uses os.exec to command communicate with the docker daemon. The approach is sound, however, I find forking out to use docker-cli to be a bit clunky. Docker’s client for go is pretty good and offers imho, a better way to achieve the same. It adds a dependency to the code, however, I believe that is a good thing. The real dependency here is the daemon on the underlying system. Taking a dependency in Go code, makes the management of the API easier and offers more control than relying on the cli api silently. Moreover, if you only use the dependency in your _test.go files, it won’t impact the final build binary (or that’s my understanding atleast, someone correct me if I’m wrong). In most cases the exec approach is perhaps good enough and the right thing to do, but I have an alternative.
...