Lesson 86 of 93 · 6 min read · Updated

Start Only the Infrastructure a Test Needs: Container Fixtures with Testcontainers

A real container costs time: the image must be pulled once, and every start takes seconds. A test suite that starts PostgreSQL, Redis, RabbitMQ and Kafka for every run makes a developer wait for all four, even when they only want to run one cache test. This lesson shows how to split container fixtures so each test class starts only the infrastructure its scenario needs, and how to configure each container so the setup stays predictable.

Technical Requirements

  1. .NET 11 SDK
  2. Docker
  3. Testcontainers.PostgreSql, Testcontainers.Redis, Testcontainers.RabbitMq and Testcontainers.Kafka 4.17.0
  4. StackExchange.Redis 3.4.35, RabbitMQ.Client 7.2.2, Confluent.Kafka 2.16.0
  5. xUnit 2.9.3

Group Containers by the Scenarios That Use Them

The ticket API in this example uses PostgreSQL for storage and Redis as a cache. Many tests need both: the cache-aside test reads from the database and writes to the cache. These two containers therefore live together in one fixture, InfrastructureFixture, and start in parallel:

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

// The image tag is passed to the constructor EXPLICITLY: "latest" is never used.
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:17-alpine")
.WithDatabase("tickets")
.WithUsername("tester")
.WithPassword("tester-parolasi")
.WithCleanUp(true) // Remove the container when the tests finish.
.Build();

private readonly RedisContainer _redis = new RedisBuilder("redis:7-alpine")
.WithCleanUp(true)
.Build();

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

public async Task InitializeAsync()
{
// We start the two containers IN PARALLEL: this saves the suite seconds.
// StartAsync waits UNTIL the container is READY (wait strategy);
// an observable condition instead of "waiting and hoping" with Thread.Sleep.
await Task.WhenAll(_postgres.StartAsync(), _redis.StartAsync());

Task.WhenAll starts both containers at the same time, so the fixture waits for the slower one instead of the sum of both. Each StartAsync() returns only when its wait strategy reports the service ready. The PostgreSQL module waits until the server accepts connections, so the first query never hits a database that is still booting. You never need Thread.Sleep to "give it a moment".

The message brokers are different. Only the RabbitMQ and Kafka test classes use them. If they were added to the same fixture, every database test would also wait for a Kafka broker to start. So each broker gets its own fixture:

M10.ContainerApi.Tests/Infrastructure/BrokerFixtures.cs

public sealed class RabbitMqFixture : IAsyncLifetime
{
private readonly RabbitMqContainer _rabbitMq = new RabbitMqBuilder("rabbitmq:4.1-alpine")
.WithCleanUp(true)
.Build();

public IConnection Connection { get; private set; } = null!;

public async Task InitializeAsync()
{
// StartAsync waits until the AMQP port accepts connections (wait strategy).
await _rabbitMq.StartAsync();

var factory = new ConnectionFactory { Uri = new Uri(_rabbitMq.GetConnectionString()) };
Connection = await factory.CreateConnectionAsync();
}

public async Task DisposeAsync()
{
await Connection.DisposeAsync();
await _rabbitMq.DisposeAsync();
}
}

The RabbitMQ test class asks for this fixture with IClassFixture<RabbitMqFixture>. xUnit creates the fixture only when that class runs. If you filter the run to the Redis tests, RabbitMQ is never started.

FixtureContainersUsed by
InfrastructureFixture (collection fixture)PostgreSQL + RedisDatabase, Respawn and cache tests
RabbitMqFixture (class fixture)RabbitMQRabbitMqMessagingTests only
KafkaFixture (class fixture)KafkaKafkaMessagingTests only

The rule behind this split is simple: the scenario decides the infrastructure, not the project. Ask which real services a test class must talk to, and give it exactly those. A fixture that starts "everything the application uses" feels convenient at first. As the system grows, it turns every small test run into a full environment start, and developers stop running the tests locally.

The broker fixture also creates the RabbitMQ connection once. Opening an AMQP connection is not free, so the tests share it and open cheap channels on it instead.

Pin Every Image Tag

All four builders receive an explicit tag: postgres:17-alpine, redis:7-alpine, rabbitmq:4.1-alpine and confluentinc/cp-kafka:7.9.0.

Common mistake: using latest or no tag at all. Then the image your tests run against changes whenever the vendor publishes a new release. One morning the suite fails, and nothing in your repository changed. A pinned tag makes the test environment part of your source code. You upgrade it on purpose, in a commit, and the CI run on that commit tells you whether the new version breaks anything. The same tags are reused in the CI workflow and in the Aspire AppHost, so every environment runs the same versions.

Configure the Container for Tests, Not for Production

A container's defaults are tuned for production. Sometimes a default makes tests slow or flaky, and the fixture is the place to change it. The Kafka fixture is a good example:

M10.ContainerApi.Tests/Infrastructure/BrokerFixtures.cs

/// <summary>
/// Kafka fixture.
///
/// KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0: by default the broker makes a new
/// consumer group wait 3 seconds (it avoids needless rebalances in production).
/// In a test this is only slowness; we set it to zero.
/// </summary>
public sealed class KafkaFixture : IAsyncLifetime
{
private readonly KafkaContainer _kafka = new KafkaBuilder("confluentinc/cp-kafka:7.9.0")
.WithEnvironment("KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS", "0")
.WithCleanUp(true)
.Build();

public string BootstrapServers => _kafka.GetBootstrapAddress();

public Task InitializeAsync() => _kafka.StartAsync();

public Task DisposeAsync() => _kafka.DisposeAsync().AsTask();

Every Kafka test creates a new consumer group. Without this setting, each of them would wait three extra seconds before receiving its first message.

The fixture also creates topics explicitly instead of relying on automatic topic creation:

/// <summary>
/// Creates the topic EXPLICITLY. Relying on auto-creation means leaving the
/// partition count to the broker default and a race condition on the first message.
/// </summary>
public async Task CreateTopicAsync(string topic, int partitions)
{
using var admin = new AdminClientBuilder(
new AdminClientConfig { BootstrapServers = BootstrapServers }).Build();

await admin.CreateTopicsAsync(
[
new TopicSpecification { Name = topic, NumPartitions = partitions, ReplicationFactor = 1 },
]);
}

A test about message ordering needs to know how many partitions the topic has. If the broker decided, the test would depend on a value it never states.

The Redis connection is configured for tests too. The fixture sets AllowAdmin = true so it can run FLUSHDB between tests:

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

// allowAdmin: needed for admin commands such as FLUSHDB.
// Deterministic RESET between tests depends on it; do NOT enable it in production.
var redisOptions = ConfigurationOptions.Parse(_redis.GetConnectionString());
redisOptions.AllowAdmin = true;

Redis = await ConnectionMultiplexer.ConnectAsync(redisOptions);

This is fine for a throwaway container. In production code, admin commands should stay disabled.

Summary

  1. Put containers that are used together in one fixture, and start them in parallel with Task.WhenAll.
  2. Give infrastructure that only a few test classes need its own IClassFixture, so it starts only when those classes run.
  3. Rely on StartAsync() and its wait strategy instead of fixed delays.
  4. Pin every image tag; latest lets an outside release break your suite.
  5. Tune container settings for tests in the fixture, such as Kafka's rebalance delay or explicit topic creation.