Hello everyone, in today’s post I will show you the easiest and cleanest way to perform integration testing of your code with database dependencies with the help of docker and TestContainers.
Unlike unit tests where you can use In-Memory or Mock the database calls, integration tests need to test the actual calls to the database, and using an empty, In-Memory, database will not represent the reality of what the system is doing, or perhaps your code is tightly coupled with specific database behaviors or relies on certain configurations that an In-Memory setup won’t capture accurately. For that, we will use docker to run a dockerized database image and perform our tests against it. And for that, we will use TestContainers.
Stay In Touch
Subscribe to our mailing list to stay updated on topics and videos related to .NET, Azure, and DevOps!
By submitting your information, you’re giving us permission to email you. You may unsubscribe at any time.
What is TestContainers?
TestContainers is a .NET library that simplifies the management of Docker containers for testing. It provides an API to interact with containers directly from your test suite, supporting a wide range of services, including popular databases such as SqlServer, MySQL, PostgreSQL, and MongoDB, along with other services like Selenium for browser automation or RabbitMq for message broker tests. We will focus on one notable TestContainers module, the Azure SQL Edge module, which allows an easy setup of Azure SQL Edge instances in Docker for testing. This will enable us to configure our test environment very similar to our production apps hosted in Azure using Azure SQL Database.
Add TestContainers to your test project
To view the source code of this project, check it out on my GitHub repository github/mhdbouk/testcontainers-demo
To begin with TestContainers, we can start by adding the following NuGet packages to your test project:
dotnet add package Testcontainers.SqlEdge
Then, to create and use the Testcontainer, add the following to the test
var container = new SqlEdgeBuilder()
.WithImage("mcr.microsoft.com/azure-sql-edge")
.Build();
await container.StartAsync();
var connectionString = container.GetConnectionString();
This code will create and run a docker container with mcr.microsoft.com/azure-sql-edge image - the offical azure image - and container.GetConnectionString()
will return the connectionString of that database server so we can use it to create our DB Context
var context = new TodoDbContext(new DbContextOptionsBuilder<TodoDbContext>().UseSqlServer(container.GetConnectionString()).Options);
await context.Database.EnsureCreatedAsync();
var repository = new TodoRepository(context);
// Perform the tests on the repository
Make sure that Docker is running when you run the tests.
Happy testing and coding!