Skip to content
Skywalk Innovations > Software Development > Using test containers for integration tests in C#

Using test containers for integration tests in C#

Background

In almost all of our applications we have a database that we write to. We have multiple ways we write to said databases, such as Dapper or Entity Framework. We also connect to multiple venders databases, such as MySql, Sql Server, and Mongo. For our integration testing we connect to a database to test our services.

Problem Faced

In order to write these integration tests we need to have a database for whatever we our using the application running or replicate the functionality using a fake or mock of the database. These needs to be repeatable in a build pipeline. 

Alternatives Explored

We have tried using Sqllite as an alternative when running integration tests. This was only applicable when we were using a Sql database in production. We also attempted to use mocking libraries specifically made to make DbSets when working with Entity Framework. These libraries were difficult to get setup and did not support all of the extension methods available for Entity Framework. They were also not applicable when using Dapper. 

Benefits of the current approach

The current approach we decided to go with is to start up a container for the database when we run a test session. The advantages of this approach is that you a likely to find a docker image for the database vender you are using, you can easily replicate the version of the database you using in production, and you can clear out a database after each test session. We also decided to setup these containers in test sessions themselves so as manage the setup in code, this can be done using test container as illustration below.  

Setting up the Project

Define Your Service Class

Configure Dependency Injection in Test Setup

Writing Integration Tests

Join the Revolution in Testing!

Eager to take your integration testing to the next level? Embrace the efficiency of Testcontainers and see the difference for yourself. Whether you’re battling database dilemmas or just looking for a more streamlined testing process, our methods are proven to enhance productivity and reliability. Don’t just take our word for it—try it out in your next project!

Picture of Geoffrey Mouton

Geoffrey Mouton

Senior Software Engineer at Skywalk Innovations