Integration Testing with Testcontainers

“It works on my machine” usually means “I have a local SQL Server running”. This breaks in CI. Testcontainers is the solution.

Ephemeral Infrastructure

Testcontainers spins up a real Docker container for your test, runs the test, and throws it away.

public class CustomerRepositoryTests : IAsyncLifetime
{
    private readonly MsSqlContainer _dbContainer = new MsSqlBuilder().Build();

    public async Task InitializeAsync()
    {
        await _dbContainer.StartAsync();
        // Run migrations on the fresh container...
    }

    [Fact]
    public async Task Should_Save_Customer()
    {
        var connStr = _dbContainer.GetConnectionString();
        // Test against REAL SQL Server!
    }
}

This means you are testing against the exact version of SQL Server (or Redis, or RabbitMQ) you use in production, not a mock.


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.