Database integration tests with docker

Nick Lydon
2 min readJan 26, 2022

--

I like to have integration tests for these reasons:

  1. The repository or SQL logic can be complex.
  2. Hand-rolled SQL isn’t type-checked, so we rely on automated testing.
  3. In-memory mocks conceal database vendor-specific details that don’t show up until running against the real thing.

It’s very easy to create database integration tests using a library called Testcontainers. I’ve been using the port dotnet-testcontainers in order to write tests for dotnet applications using entity framework. The library spins up a docker container for the database and then the test executes the entity framework migrations against a database on that server.

I’ve set up a simple example project on github, that includes everything needed to get started:

  1. Entity framework migrations
  2. Unit tests
  3. The integration with the testcontainer library

All you need to do is start docker, clone the repo and run dotnet test IntegrationTests in your terminal.

The reason that it creates a single docker container and multiple unique databases is for performance. Spinning up a container can take a long time, so it makes sense to only do this once. We want the tests to be isolated to ensure that they don’t conflict (especially when run in parallel), so we use a database instance per test. After the last test has finished, the class fixture stops the docker container to prevent it from consuming resources.

Using this strategy it’s possible to have tests that work in your local development environment, but also more importantly as part of the continuous integration build. When integrated inside an azure devops pipeline that runs on the latest ubuntu build agents, this doesn’t require any additional configuration.

--

--

Nick Lydon
Nick Lydon

Written by Nick Lydon

British software developer working as a freelancer in Berlin. Mainly dotnet, but happy to try new things! https://github.com/NickLydon

No responses yet