This blog post aims to guide you through an alternative way of running integration tests within your project. We look to make use of Testcontainers which support tests with throwaway instances of Docker containers. A list of the pre-configured containers can be found here. This means we can run tests without going to a deployed instance of the service we look to integrate with, saving time on round-trip-times. All code talked about in this post will be available here.
For the purposes of our project, an integration test is defined as an automated test written to test the interaction between code that we have written with a third party service. The goal is to prove that the code can communicate as expected with the third party service so that we can identify any defects before it reaches a later stage of the development cycle.
We will use Docker containers. To follow along, you will need to have Docker (or equivalent) set up and running. Testcontainers will spin up container instances which will be used to execute tests against. Each test will have a dedicated container instance so that tests can be run in parallel without affecting other tests.
By using a container, we can execute tests locally without depending on the third party service to host an instance and we can execute each test against a new instance of the third party service without having to set up anything locally.
For this example, we will test a class that will integrate with Redis. I've created two projects, one to contain the class that will be tested and another to execute tests.
The test we want to execute needs to interact with the instance of redis. We need each test to:
The DotNet NuGet Testcontainers (currently version 2.20) gives us the ability to spin up container instances per test. For Redis there is a pre-configured RedisTestcontainer we can use to provide us an instance of redis within a container.
This blog post has shown that we can execute integration tests locally which target a Docker container. Anyone with Docker installed and running can clone this repository, build and test it. They are not required to install or provision an instance of Redis to execute these tests. This should help speed up and improve the development process.
There are limitations:
This repository is actively being developed and there are already people developing a cosmos and azurite Testcontainer setup class. As these get introduced, it will be quicker and easier to get started with these services.
Chris Butler is a Senior .Net Consultant at Ensono Digital specialising in Cloud Services and Behaviour-Driven Development. He has over 11 years experience supporting some of the UK's leading businesses solve their most complex engineering issues.