Lesson 90 of 93 · 7 min read · Updated

Testing RabbitMQ and Kafka with Testcontainers: Real Brokers, Real Protocols

An in-memory fake queue can tell you that your code called Publish. It cannot tell you whether the broker routed the message to the right queue, whether the bytes on the wire match the contract, or whether an unacknowledged message really comes back after a consumer crash. This lesson tests a RabbitMQ publisher and a Kafka publisher against real brokers started by Testcontainers, and shows three rules that keep such tests fast and stable.

Technical Requirements

  1. .NET 11 SDK
  2. Docker
  3. Testcontainers.RabbitMq and Testcontainers.Kafka 4.17.0
  4. RabbitMQ.Client 7.2.2 and Confluent.Kafka 2.16.0
  5. Testcontainers.Redis 4.17.0 and StackExchange.Redis 3.4.35 for the cache example
  6. xUnit 2.9.3 and FluentAssertions 7.2.2

Three Rules for Broker Tests

All broker tests share one container per test class, so they follow three rules:

  1. Give every test unique exchange, queue, topic and consumer group names, so tests on a shared broker never see each other's messages.
  2. Wait for an observable condition with a time limit, never for a fixed Sleep.
  3. Assert on the business events that were published and consumed, not on infrastructure calls.

The first rule is one line of code in each test class:

M10.ContainerApi.Tests/RabbitMqMessagingTests.cs

private static string Unique(string name) => $"{name}-{Guid.NewGuid():N}";

RabbitMQ: Body, Properties and Topic Routing

The publisher writes a TicketCreated event to a topic exchange. The routing key carries the priority, for example ticket.created.high:

M10.ContainerApi/Messaging/RabbitMqTicketEventPublisher.cs

public async Task PublishAsync(TicketCreated @event, CancellationToken cancellationToken = default)
{
var properties = new BasicProperties
{
ContentType = "application/json",
// Persistent message: it is not lost even if the broker restarts.
DeliveryMode = DeliveryModes.Persistent,
// Lets the consumer filter out duplicate processing (idempotency).
MessageId = @event.Reference,
Type = TicketCreated.EventType,
};

await channel.BasicPublishAsync(
exchange,
RoutingKeyFor(@event.Priority),
mandatory: false,
basicProperties: properties,
body: TicketEventSerializer.Serialize(@event),
cancellationToken: cancellationToken);
}

The tests publish on a channel with publisher confirms turned on. Then BasicPublishAsync returns only after the broker has accepted and routed the message, so the next assertion does not race the broker:

M10.ContainerApi.Tests/Infrastructure/BrokerFixtures.cs

public Task<IChannel> CreateConfirmingChannelAsync() =>
Connection.CreateChannelAsync(new CreateChannelOptions(
publisherConfirmationsEnabled: true,
publisherConfirmationTrackingEnabled: true));

The first test consumes the message and checks everything a consumer depends on. The consumer writes deliveries into a System.Threading.Channels channel, and the test reads from it with a ten-second timeout:

M10.ContainerApi.Tests/RabbitMqMessagingTests.cs

// The consumer writes incoming messages to a Channel; the test reads from it with a TIME LIMIT.
var received = Channel.CreateUnbounded<BasicDeliverEventArgs>();
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (_, delivery) =>
{
// The body is recycled when the handler finishes: store a COPY.
await received.Writer.WriteAsync(CopyOf(delivery));
await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false);
};
await channel.BasicConsumeAsync(queue, autoAck: false, consumer);

var publisher = new RabbitMqTicketEventPublisher(channel, exchange);
var published = NewEvent("DST-3001", TicketPriority.High);

// Act
await publisher.PublishAsync(published);

// Assert: NO fixed delay; continue when the message arrives or the time runs out.
using var cts = new CancellationTokenSource(Timeout);
var delivery = await received.Reader.ReadAsync(cts.Token);

TicketEventSerializer.Deserialize(delivery.Body.Span).Should().Be(published);
delivery.RoutingKey.Should().Be("ticket.created.high");
delivery.BasicProperties.ContentType.Should().Be("application/json");
delivery.BasicProperties.MessageId.Should().Be("DST-3001");
delivery.BasicProperties.Type.Should().Be(nameof(TicketCreated));

// The wire contract: the enum travels as TEXT.
Encoding.UTF8.GetString(delivery.Body.Span).Should().Contain("\"priority\":\"High\"");

Pitfall: the client library reuses the body buffer after the event handler returns. If you store delivery directly and read Body later, you may read another message's bytes. The CopyOf helper copies the body with delivery.Body.ToArray() before the handler ends.

The last assertion checks the raw bytes. The serializer writes enums as strings, so reordering the TicketPriority enum can never turn "High" into "Critical" for an older consumer. Only a test that reads real bytes from a real broker can prove this contract.

A second test binds an "urgent" queue only to the high and critical routing keys, publishes three events, and asserts that the urgent queue holds exactly one message while the catch-all queue holds three. Routing is the broker's job, so a fake cannot test it.

RabbitMQ: Redelivery After a Crash

This test simulates a consumer that takes a message and crashes before it acknowledges it:

M10.ContainerApi.Tests/RabbitMqMessagingTests.cs

// Act: the first consumer TAKES the message but "crashes" without an ACK (the channel closes).
var crashingConsumer = await fixture.Connection.CreateChannelAsync();
var firstAttempt = await crashingConsumer.BasicGetAsync(queue, autoAck: false);
firstAttempt.Should().NotBeNull();
firstAttempt!.Redelivered.Should().BeFalse("first delivery");
await crashingConsumer.CloseAsync();
await crashingConsumer.DisposeAsync();

// Assert: the broker puts the message BACK on the queue and delivers it again.
await using var healthyConsumer = await fixture.Connection.CreateChannelAsync();
var secondAttempt = await WaitForMessageAsync(healthyConsumer, queue);

secondAttempt.Redelivered.Should().BeTrue("an unacknowledged message is not lost, it comes back");
TicketEventSerializer.Deserialize(secondAttempt.Body.Span).Reference.Should().Be("DST-4001");

// The consumer must be idempotent: the same MessageId can arrive twice.
secondAttempt.BasicProperties.MessageId.Should().Be(firstAttempt.BasicProperties.MessageId);

WaitForMessageAsync polls the queue every 50 ms until a message appears or ten seconds pass, then throws a TimeoutException with a clear message. The test never hangs forever, and it finishes as soon as the condition is met. The MessageId check shows why consumers must be idempotent: at-least-once delivery means the same event can arrive twice.

Kafka: Ordering per Key and Committed Offsets

The Kafka publisher uses the customer's e-mail as the message key. Kafka always writes the same key to the same partition, and it guarantees order only within a partition. The test publishes interleaved events for two customers to a three-partition topic:

M10.ContainerApi.Tests/KafkaMessagingTests.cs

// Arrange: a topic with 3 partitions: order is NOT guaranteed across the whole topic.
var topic = Unique("ticket-events");
await fixture.CreateTopicAsync(topic, partitions: 3);

using var producer = fixture.CreateProducer();
var publisher = new KafkaTicketEventPublisher(producer, topic);

// Act: the tickets of two customers are published interleaved.
for (var i = 1; i <= 5; i++)
{
await publisher.PublishAsync(NewEvent($"AYSE-{i}", "ayse@ornek.com"));
await publisher.PublishAsync(NewEvent($"MEHMET-{i}", "mehmet@ornek.com"));
}

using var consumer = fixture.CreateConsumer(Unique("ordering-group"));
consumer.Subscribe(topic);
var results = ConsumeExactly(consumer, 10);

// Assert: for each customer, ONE partition and the publish order is preserved.
foreach (var customer in new[] { "ayse@ornek.com", "mehmet@ornek.com" })
{
var ofCustomer = results.Where(r => r.Message.Key == customer).ToList();

ofCustomer.Select(r => r.Partition.Value).Distinct().Should().ContainSingle(
"the same key is always written to the same partition");

var prefix = customer.StartsWith("ayse") ? "AYSE" : "MEHMET";
ofCustomer.Select(r => TicketEventSerializer.Deserialize(r.Message.Value).Reference)
.Should().Equal(Enumerable.Range(1, 5).Select(i => $"{prefix}-{i}"));
}

ConsumeExactly reads until it has the expected number of messages or 30 seconds pass:

while (results.Count < count && DateTime.UtcNow < deadline)
{
var result = consumer.Consume(TimeSpan.FromMilliseconds(250));
if (result is not null && !result.IsPartitionEOF)
{
results.Add(result);
}
}

A third test, ConsumerGroup_ResumesFromCommittedOffset_AfterRestart, processes two events, commits the offset, publishes a third event and starts a new consumer in the same group. It asserts that the first message after the restart is the third event. To prove "no old messages came back", it does not wait a fixed time for silence. It checks that the known latest event is the first one to arrive. A brand new group, in contrast, reads all three events from the beginning.

Redis: When a Delay Is the Scenario

The cache tests follow the same rules, with one interesting exception:

M10.ContainerApi.Tests/RedisCacheTests.cs

[Fact]
public async Task Cache_HonoursTimeToLive()
{
// TTL behaviour CANNOT be tested with an in-memory dictionary.
// We use a short TTL here; the wait is BOUNDED and observable.
var cache = fixture.CreateCache();

await cache.SetAsync(NewTicket("DST-TTL"), TimeSpan.FromMilliseconds(300));

(await cache.GetAsync("DST-TTL")).Should().NotBeNull();

await Task.Delay(TimeSpan.FromMilliseconds(600));

(await cache.GetAsync("DST-TTL")).Should().BeNull("TTL expired");
}

This test does wait a fixed 600 ms, and that is acceptable: the passing of time is the behaviour under test, not a guess about when a background process finishes. The wait is twice the TTL, so it does not depend on exact timing.

Summary

  1. Real brokers prove what fakes cannot: routing, wire format, redelivery, partition ordering and committed offsets.
  2. Use unique queue, topic and group names in every test so a shared broker stays clean.
  3. Replace Thread.Sleep with a bounded wait on an observable condition, and fail with a clear timeout message.
  4. Turn on publisher confirms in RabbitMQ tests so counts and assertions do not race the broker.
  5. Assert on the business events and the bytes on the wire, and design consumers to be idempotent.