Unit-testing with xUnit and TestContainers

Albert Starreveld
3 min readFeb 17, 2023

Some things are hard to test. Executing Stored procedures with EntityFrameworkCore for example. Stored procedures don’t work with an in-memory dbContext or with Sqlite. To test it, you’ll need a running instance of SQL Server.

Testing with dependencies on infrastructure is not ideal because it requires configuration to be similar across development machines and build agents. Containerizing the infrastructure with Docker can ease the pain.

And then there’s the issue of unit testing in general. A proper unit test has some important characteristics:

  • Unit tests should be able to run multiple times in a random order without it having an impact on the test results.
  • A unit test should have three stages. It should have an “arrange” stage in which the preconditions are set, it should have an “act” in which the subject under test is executed, and it should have an “assert” in which the results are validated.

This implies that ideally when you are using a Docker container for testing purposes, you will need to spin it up, run the test, remove it, and do this for every test.

There’s a .NET library called TestContainers that allows you to do exactly that. Check out https://dotnet.testcontainers.org/

Read this blog if you want to learn:

  • How to apply test containers with xUnit
  • How to test a stored procedure with Entity Framework and test containers

Spinning up a Docker container from code

A test container is a throwaway instance of a Docker container. You can spin up any Docker image you want, as long as it’s in a container registry. In this case, I want to spin up an instance of SQL Server. To start a SQL Server image with Docker, execute the following command:

& docker run `
-e "ACCEPT_EULA=Y" `
-e "MSSQL_SA_PASSWORD=nunajabeezwax" `
-p 1433:1433 `
-d mcr.microsoft.com/mssql/server:2022-latest

To use this image with test containers, use the following C# code:

Creating an async setup- and teardown…

--

--

Albert Starreveld

Passionate about cloud native software development. Only by sharing knowledge and code we can take software development to the next level!