Kafka and Redpanda integration tests with Testcontainers
Java integration tests often need to prove that a producer can publish, a broker can retain a record, and a consumer can process it. Mocking those pieces is fast, but it can hide protocol, serialisation, offset, and consumer-group faults. A disposable broker container gives the test a real network boundary while keeping setup and teardown deterministic.
Testcontainers makes that pattern practical. It starts Apache Kafka or Redpanda in Docker, exposes a mapped host port, and removes the container after the test. The same Java client and application code can then exercise topics, acknowledgements, partitions, retries, and consumer behaviour without relying on a shared development cluster.
For teams in Sydney and Melbourne, this also removes brittle VPN routes and credentials from routine test runs. The approach supports Java, JUnit 5, Spring Boot, Gradle, and Maven pipelines, giving local checks and continuous delivery the same broker semantics. A broker that behaves consistently across both environments makes failures easier to reproduce and local experiments more representative.
Why use real brokers in Java tests
A containerised broker is valuable because the risk sits between components, not inside them. Topic creation can fail, advertised listeners can point at the wrong address, and a consumer may subscribe before it is ready to receive. These are exactly the behaviours that lightweight mocks tend to remove.
| Consideration | Apache Kafka | Redpanda |
|---|---|---|
| Client compatibility | Native Kafka protocol and Java clients | Kafka-compatible protocol with common Java clients |
| Deployment model | Brokers and controllers, commonly using KRaft | A single binary in development or its own clustered configuration |
| Administration | Kafka AdminClient and a mature Kafka ecosystem | Common Kafka administration operations plus Redpanda-specific APIs |
| Main test caveat | Kafka policies and features can influence results | Compatibility does not mean identical administration, storage, or transaction behaviour |
Compatibility needs a precise meaning. Redpanda speaks the Kafka protocol and supports common client operations, yet its administration APIs, storage features, and some transactional or consumer-group details can differ. A successful test against one broker is evidence of application behaviour on that broker, not a guarantee that every production feature transfers unchanged. Contract tests should distinguish protocol compatibility from operational compatibility.
Keep each test's data space small. Generate a unique topic name and consumer-group identifier, use the earliest offset only when the test needs existing history, and avoid sharing mutable records across cases. Testcontainers isolates the broker process; unique names provide the logical isolation that the container itself does not. Delete topics only when retention behaviour is what the test examines.
Kafka and Redpanda side by side
Apache Kafka is the natural choice when the service already depends on Kafka-specific administration, partition assignment, transactions, or ecosystem tooling. Testcontainers can run the same Kafka release used by staging, and a Kafka client then exercises the real protocol implementation rather than a simulation. That gives confidence about broker discovery, record metadata, and the coordination between producers and consumers.
Redpanda can be equally useful where the application relies on the Kafka client contract but the development or self-managed environment uses Redpanda. Its container starts quickly for a single-node test and presents a Kafka-compatible endpoint. The test should still avoid assuming that every Kafka CLI command, configuration property, administrative metric, or failure message behaves identically.
Treat the broker as part of the contract, not merely a transport. Run a shared business-contract suite against Kafka and Redpanda when the application supports both, and keep broker-specific checks in separate classes. Record the tested broker, image tag, and relevant feature requirements in the test report. This exposes meaningful incompatibilities early without forcing unused production features into every test.
Wire a broker into JUnit
Pin the Testcontainers library and broker image. An explicit tag makes a failure reproducible and prevents a moving image from changing broker defaults between local and CI runs. The JUnit module supplies the lifecycle annotations, while the broker modules supply the specialised containers.
<properties>
<testcontainers.version>1.20.4</testcontainers.version>
</properties>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>kafka</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>redpanda</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
A Spring Boot integration test can inject the mapped broker address through dynamic properties. A static container is reused across the methods in that test class, reducing startup overhead while preserving a fresh broker for each class.
@SpringBootTest
@Testcontainers(disabledWithoutDocker = true)
class OrderEventIntegrationTest {
@Container
static final KafkaContainer kafka =
new KafkaContainer("confluentinc/cp-kafka:7.6.1");
@DynamicPropertySource
static void brokerProperties(DynamicPropertyRegistry registry) {
registry.add("spring.kafka.bootstrap-servers", kafka::getBootstrapServers);
}
}
For Redpanda, replace the container with new RedpandaContainer("redpandadata/redpanda:v24.1.8"); the dynamic property remains unchanged. Keep the application-facing configuration identical so the test compares broker behaviour rather than two different wiring mechanisms. The disabledWithoutDocker option suits local development, but CI should separately enforce the availability of its Docker service.
Assert asynchronous delivery
A container being ready does not mean the consumer is ready. Create the topic explicitly, confirm cluster metadata through AdminClient, start the consumer, publish the event, and then wait for the observable result with a bounded polling loop. Awaitility can provide the timeout and useful failure message, but every poll needs a finite deadline so a broken event path cannot stall the build.
Use a unique topic and group for each scenario, then assert on the business outcome rather than a fixed sleep. Track the record key or order identifier so parallel tests cannot accidentally consume one another's messages. Also assert that no unexpected record arrives when ordering, deduplication, or filtering is part of the requirement.
Local data can expose timing bugs that generic fixtures miss. A retail test might publish an au.order-events.v1 record for an AUD 149.95 purchase or an Australian customs-clearance event, then assert the downstream shipment state. Include an explicit Australia/Sydney offset and cover daylight-saving transitions; a UTC-only fixture can conceal Australian scheduling defects. This emphasis on observable outcomes also aligns with the broader testing perspective published by Ahmad Sanusi Husain.
Run containers in continuous delivery
The CI runner needs access to a Docker daemon, adequate memory, and permission to publish and listen on ephemeral ports. Australian development teams commonly mix Apple silicon and Intel-based machines, so verify that the pinned broker image supports both architectures instead of relying on slow emulation. Cache the image by tag, but pre-pull it in the job to separate registry problems from application failures.
Parallel workers need separate broker containers or carefully partitioned topics and consumer groups. Avoid enabling container reuse in shared CI because retained topics and groups undermine test isolation. Maven can run integration-test classes named *IT through Failsafe, while Gradle usually places them in an integrationTest source set. Testcontainers cleanup normally handles normal termination, while its reaper process can remove containers left behind by an interrupted JVM.
A disposable test broker is not a substitute for a managed production environment. For Australian workloads, a hosted Kafka service may run in AWS's Sydney region, ap-southeast-2, while contractual or Australian Privacy Act obligations may require data to remain in an approved jurisdiction. Keep customer and payment records out of CI, use synthetic AUD transaction data, and test production-region constraints separately.
Keep failures useful and the suite maintainable
Capture broker logs, topic metadata, consumer-group state, and the relevant record keys when an assertion fails. Container removal is convenient, but CI should export logs first; otherwise the most useful evidence disappears with the broker. Include the generated topic name in assertion messages so a retry can reproduce the same path. Container inspection output can also reveal port mapping or listener configuration problems.
Pin image tags and keep one contract suite that can run against both Kafka and Redpanda. Label tests by the behaviour they require, such as general Kafka protocol compatibility or Redpanda administration, rather than duplicating entire suites. Avoid asserting incidental details such as controller IDs or exact partition placement unless the production contract requires them. Review broker-version changes as deliberate compatibility events.
Testcontainers validates functional integration, not production throughput. Performance runs need representative client settings, data volumes, disk, and network conditions in a controlled environment. The concrete next step is to add one Testcontainers-backed *IT test to the next service release and run it in the continuous integration pipeline.