Introduction
Integration testing often feels like a luxuryâsomething we skip when deadlines loom. But what if spinning up real dependencies (databases, message brokers, APIs) was as easy as writing a unit test? Thatâs where Testcontainers comes in.
The Problem
Traditional integration tests rely on shared dev environments or mocked services. Both approaches introduce fragility:
- Shared environments = flaky tests due to state pollution
- Mocks = false confidence, since they donât reflect production reality
The Solution: Testcontainers
Testcontainers lets you run real dependencies inside lightweight Docker containers, directly from your test code. Imagine testing against a real Azure SQL Database or Kafka broker without touching your local setup.
Example in .NET
public class SqlIntegrationTests : IAsyncLifetime
{
private readonly MsSqlContainer _sqlContainer = new MsSqlBuilder().Build();
public async Task InitializeAsync() => await _sqlContainer.StartAsync();
public async Task DisposeAsync() => await _sqlContainer.DisposeAsync();
[Fact]
public async Task CanInsertAndRetrieveData()
{
using var connection = new SqlConnection(_sqlContainer.GetConnectionString());
await connection.OpenAsync();
var command = new SqlCommand("CREATE TABLE Users(Id INT, Name NVARCHAR(100));", connection);
await command.ExecuteNonQueryAsync();
var insert = new SqlCommand("INSERT INTO Users VALUES(1, 'Printo');", connection);
await insert.ExecuteNonQueryAsync();
var reader = new SqlCommand("SELECT Name FROM Users WHERE Id=1;", connection).ExecuteReader();
reader.Read().Should().BeTrue();
reader.GetString(0).Should().Be("Printo");
}
}
Why This Matters
- â Confidence: Youâre testing against real services, not mocks.
- â Portability: Works on any machine with Docker.
- â Speed: Containers spin up fast and die cleanly after tests.
Beyond Databases
Testcontainers supports Redis, RabbitMQ, Kafka, Elasticsearch, and more. You can even run custom Docker images for niche services.
Closing Thought
Integration testing doesnât have to be painful. With Testcontainers, you can build trust in your systemâone container at a time.
Top comments (0)