Unit-testing with xUnit and TestContainers
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