gitmyhub

dockertest

Go ★ 4.5k updated 7h ago

Write better integration tests! Dockertest helps you boot up ephermal docker images for your Go tests with minimal work.

dockertest is a Go library that makes it easy to spin up real database and service containers during automated tests. The problem it solves is a common one in software development: when your code talks to a database, testing it properly requires either a real database or a fake one. Faking a database is tedious and fragile, because any change to your schema or queries means rewriting all the fakes. Running tests against a real database is more reliable but messy to set up. Docker, a system that can launch isolated software containers in seconds, is a good solution here, and dockertest wraps that capability into a simple Go API.

The library handles the boilerplate of starting a container, waiting until the service inside it is actually ready to accept connections, running your tests, and then stopping and removing the container automatically. The waiting step matters because Docker can report a container as running before the database process inside it is accepting connections, which would cause tests to fail with confusing errors. dockertest includes a retry loop that calls a check function you provide, repeating until the service responds or a timeout is reached.

Out of the box, the library has built-in support for starting PostgreSQL, MySQL, MongoDB, Redis, Cassandra, RabbitMQ, Elasticsearch, and several other services. It also allows starting any custom Docker image when the built-in options do not cover what you need.

The library works on Linux, macOS, and Windows. For CI pipelines like Travis CI, it includes environment variables to control how containers bind to network interfaces. The README recommends using the newer v3 version of the library for new projects, as it has a cleaner API and fewer dependencies.