Lesson 90 of 93 · 7 min read · Updated
Testing RabbitMQ and Kafka with Testcontainers: Real Brokers, Real Protocols
On this page
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
- .NET 11 SDK
- Docker
Testcontainers.RabbitMqandTestcontainers.Kafka4.17.0RabbitMQ.Client7.2.2 andConfluent.Kafka2.16.0Testcontainers.Redis4.17.0 andStackExchange.Redis3.4.35 for the cache example- 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:
- Give every test unique exchange, queue, topic and consumer group names, so tests on a shared broker never see each other's messages.
- Wait for an observable condition with a time limit, never for a fixed
Sleep. - 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
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
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
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
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
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
ConsumeExactly reads until it has the expected number of messages or 30 seconds pass:
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
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
- Real brokers prove what fakes cannot: routing, wire format, redelivery, partition ordering and committed offsets.
- Use unique queue, topic and group names in every test so a shared broker stays clean.
- Replace
Thread.Sleepwith a bounded wait on an observable condition, and fail with a clear timeout message. - Turn on publisher confirms in RabbitMQ tests so counts and assertions do not race the broker.
- Assert on the business events and the bytes on the wire, and design consumers to be idempotent.