Testing Kafka Applications in Spring Boot
Testing Kafka applications is harder than testing a REST endpoint, because producing and consuming are asynchronous: a test sends a record and the result appears later, in another thread, maybe after a retry. Good Kafka tests therefore combine fast unit tests without a broker with a smaller number of integration tests against a real broker.
This tutorial shows the practical options for Spring Boot applications: unit tests with MockProducer, integration tests with Spring’s embedded Kafka broker, tests against a real apache/kafka container with Testcontainers, testing error handling and dead-letter topics, and testing Kafka Streams topologies without any broker.
1. Choosing the Right Kind of Test
| Approach | Speed | What it proves | What it cannot prove |
|---|---|---|---|
Plain unit tests and MockProducer | Milliseconds | Business logic, which records are sent with which keys | Serialization over the network, listener configuration, rebalancing |
TopologyTestDriver | Milliseconds | Kafka Streams logic, windows and joins with controlled timestamps | Real partitioning and repartition topics on a cluster |
@EmbeddedKafka | Seconds | Spring wiring, serializers, listeners, error handlers, transactions | Behaviour of a specific broker version or Docker networking |
| Testcontainers | Seconds (container start) | Everything above against the same broker image you run in production | Multi-broker failure scenarios, unless you start several containers |
2. Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka-test</artifactId> <!-- includes spring-kafka-test -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-kafka</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
Testcontainers 2 renamed its modules with a testcontainers- prefix; older articles use org.testcontainers:kafka, which belongs to the 1.x line.
3. The Code Under Test
The examples test a small order flow: OrderPublisher sends an event for each order, and PaymentListener consumes the events and records a payment request. Records with an invalid amount must end up in the dead-letter topic.
@Service
public class OrderPublisher {
private final KafkaTemplate<String, String> kafka;
public OrderPublisher(KafkaTemplate<String, String> kafka) { this.kafka = kafka; }
public void publish(String orderId, BigDecimal amount) {
kafka.send("orders", orderId, orderId + ":" + amount.toPlainString());
}
}
@Component
public class PaymentListener {
private final PaymentRequests payments; // stores requests; easy to inspect in tests
public PaymentListener(PaymentRequests payments) { this.payments = payments; }
@KafkaListener(topics = "orders", groupId = "payments")
public void onOrder(ConsumerRecord<String, String> record) {
BigDecimal amount = new BigDecimal(record.value().split(":")[1]);
if (amount.signum() <= 0) {
throw new IllegalArgumentException("Invalid amount " + amount);
}
payments.request(record.key(), amount);
}
}
@Configuration
public class KafkaErrorConfig {
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<String, String> template) {
var handler = new DefaultErrorHandler(new DeadLetterPublishingRecoverer(template),
new FixedBackOff(0L, 0L)); // no retries in this example
handler.addNotRetryableExceptions(IllegalArgumentException.class);
return handler;
}
}
Spring Boot applies a single CommonErrorHandler bean to the auto-configured listener container factory. The DeadLetterPublishingRecoverer sends failed records to orders-dlt, the original topic name with the -dlt suffix, in the same partition number.
4. Unit Tests Without a Broker
Most logic does not need Kafka at all: test it as plain Java. When you want to verify exactly what a component sends with the plain Kafka client, use MockProducer from kafka-clients, which records every send:
class ShipmentNotifierTest {
@Test
void sendsOneEventKeyedByOrderId() {
var producer = new MockProducer<>(true, null, new StringSerializer(), new StringSerializer());
var notifier = new ShipmentNotifier(producer); // takes a Producer<String, String>
notifier.shipped("ord-1001", "DHL-778");
assertThat(producer.history()).singleElement().satisfies(r -> {
assertThat(r.topic()).isEqualTo("shipments");
assertThat(r.key()).isEqualTo("ord-1001");
assertThat(r.value()).contains("DHL-778");
});
}
}
Passing true for auto-completion makes every send succeed immediately; with false you can call errorNext(...) to test how your code reacts to a failed send. For Spring components, mock KafkaTemplate with Mockito in the same spirit, and keep the real Kafka interaction for the integration tests below.
5. Integration Tests with @EmbeddedKafka
@EmbeddedKafka starts a KRaft broker inside the test JVM. Since Spring for Apache Kafka 3.0.10 it sets spring.kafka.bootstrap-servers automatically, so the application’s auto-configured producers and consumers connect to it without extra configuration:
@SpringBootTest(properties = "spring.kafka.consumer.auto-offset-reset=earliest")
@EmbeddedKafka(partitions = 1, topics = {"orders", "orders-dlt"})
class PaymentFlowEmbeddedTest {
@Autowired OrderPublisher publisher;
@Autowired PaymentRequests payments;
@Test
void validOrderCreatesPaymentRequest() {
publisher.publish("ord-1001", new BigDecimal("249.90"));
await().atMost(Duration.ofSeconds(10))
.untilAsserted(() -> assertThat(payments.find("ord-1001")).isPresent());
}
}
Three details make this test reliable:
auto-offset-reset=earliest: the listener’s group has no committed offset yet. With the defaultlatest, a record sent before the partition is assigned would be skipped.- Awaitility instead of
Thread.sleep: the assertion is retried until it passes or the timeout expires, so the test is as fast as the system allows. - Unique data: use distinct keys (or topics) per test, because the Spring test context, and with it the broker, is cached and shared between test classes with the same configuration.
When a test needs to read records itself, create a consumer from the broker’s properties with KafkaTestUtils.consumerProps(...) and read with KafkaTestUtils.getSingleRecord(consumer, topic); for listener containers you create in the test, ContainerTestUtils.waitForAssignment(...) waits until partitions are assigned.
6. Integration Tests with Testcontainers
Testcontainers runs the same apache/kafka image you use elsewhere. With @ServiceConnection, Spring Boot reads the container’s address and configures spring.kafka.bootstrap-servers for you:
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.kafka.KafkaContainer;
@Testcontainers
@SpringBootTest(properties = "spring.kafka.consumer.auto-offset-reset=earliest")
class PaymentFlowContainerTest {
@Container
@ServiceConnection
static KafkaContainer kafka = new KafkaContainer("apache/kafka:4.4.0");
@Autowired OrderPublisher publisher;
@Autowired PaymentRequests payments;
@Test
void validOrderCreatesPaymentRequest() {
publisher.publish("ord-2001", new BigDecimal("99.00"));
await().atMost(Duration.ofSeconds(15))
.untilAsserted(() -> assertThat(payments.find("ord-2001")).isPresent());
}
}
org.testcontainers.kafka.KafkaContainer supports the apache/kafka and apache/kafka-native images; for Confluent images use ConfluentKafkaContainer. The older org.testcontainers.containers.KafkaContainer is deprecated. Docker must be available where the tests run, including CI agents.
7. Testing Error Handling and Dead-Letter Topics
Error paths deserve tests as much as the happy path, because they are rarely exercised manually. This test sends an invalid order and asserts that it reaches the dead-letter topic, with the exception recorded in the headers:
@Autowired EmbeddedKafkaBroker broker;
@Test
void invalidOrderGoesToDeadLetterTopic() {
publisher.publish("ord-1002", new BigDecimal("-5"));
// consumerProps(...) already sets auto.offset.reset=earliest for test consumers
Map<String, Object> props = KafkaTestUtils.consumerProps("dlt-check", "true", broker);
try (Consumer<String, String> consumer = new DefaultKafkaConsumerFactory<>(
props, new StringDeserializer(), new StringDeserializer()).createConsumer()) {
broker.consumeFromAnEmbeddedTopic(consumer, "orders-dlt");
ConsumerRecord<String, String> dead = KafkaTestUtils.getSingleRecord(consumer, "orders-dlt");
assertThat(dead.key()).isEqualTo("ord-1002");
assertThat(new String(dead.headers().lastHeader(KafkaHeaders.DLT_EXCEPTION_MESSAGE).value()))
.contains("Invalid amount");
}
assertThat(payments.find("ord-1002")).isEmpty();
}
The same approach tests retry behaviour: count how often the listener is invoked, or assert on the DLT_ORIGINAL_OFFSET and DLT_EXCEPTION_FQCN headers. For non-blocking retries with @RetryableTopic, assert on the retry topics as well; see retry and backoff.
8. Testing Kafka Streams Topologies
Kafka Streams logic is best tested with TopologyTestDriver from kafka-streams-test-utils. It runs the topology synchronously, without a broker, and lets you control record timestamps, which is essential for windows:
@Test
void countsViewsPerProductInFiveMinuteWindows() {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "test");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:1234"); // never contacted
try (var driver = new TopologyTestDriver(ShopTopology.build().build(), props)) {
var in = driver.createInputTopic("product-views", new StringSerializer(), new StringSerializer());
var out = driver.createOutputTopic("product-view-counts", new StringDeserializer(), new LongDeserializer());
Instant t0 = Instant.parse("2026-12-04T10:00:00Z");
in.pipeInput("p-42", "alice", t0);
in.pipeInput("p-42", "bob", t0.plusSeconds(90));
// key = productId@windowStart, as built by the topology; the last value per key is the window count
assertThat(out.readKeyValuesToMap()).containsEntry("p-42@2026-12-04T10:00:00Z", 2L);
}
}
The topology here is the windowed count from the KStream, KTable and windowing tutorial. Both views fall into the same 5-minute window, so the latest result for that window key is 2. Because time comes only from the piped timestamps, window tests are fully deterministic.
9. Common Mistakes
- Missing records because of
latest. A new consumer group with the defaultauto.offset.reset=latestskips records sent before its partitions were assigned. Useearliestin tests. Thread.sleepas synchronisation. Fixed sleeps are either too short (flaky) or too long (slow). Use Awaitility or a latch.- Shared topics and groups between tests. Records left by one test are consumed by another. Use unique keys, topics or group IDs.
- Testing only the happy path. Deserialization errors, retries and dead-letter topics are where production incidents happen.
- Assuming per-test isolation of the embedded broker. Spring caches the context and broker across test classes with identical configuration.
- Using the deprecated Testcontainers class
org.testcontainers.containers.KafkaContainerinstead oforg.testcontainers.kafka.KafkaContainer.
10. Best Practices
- Keep business logic out of listeners so it can be unit-tested; let the listener only deserialize and delegate.
- Write a few strong integration tests per flow rather than many overlapping ones.
- Pin the broker image in Testcontainers to the version you run in production.
- Assert on observable effects (a stored row, a record in an output topic) instead of internal method calls.
- Test serialization contracts separately, for example by deserializing recorded sample payloads.
11. Summary
Test most Kafka-related code without a broker: plain unit tests, MockProducer for the client API and TopologyTestDriver for Kafka Streams. Add integration tests with @EmbeddedKafka for Spring wiring, serializers and error handlers, and with Testcontainers when you need the real broker image. Make them reliable with earliest offsets for test consumers, Awaitility instead of sleeps, and unique data per test, and always include the error path to the dead-letter topic.
12. Related Reading
- Kafka with Spring Boot: the producer and listener setup being tested
- Kafka error handling: DefaultErrorHandler and dead-letter publishing
- Testcontainers in Spring Boot: general Testcontainers setup
- Kafka Docker setup: a long-lived broker for manual development
- Spring Kafka Annotations: every Spring Kafka annotation, from @KafkaListener to @RetryableTopic and @DltHandler.
13. References
Testing Kafka Applications Interview Questions and Answers
Common interview questions on Testing Kafka Applications, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Which options do you have for testing a Spring Boot application that uses Kafka?
Answer: Unit tests without a broker for business logic, using MockProducer or a mocked KafkaTemplate; TopologyTestDriver for Kafka Streams; integration tests with Spring’s @EmbeddedKafka, which runs a KRaft broker in the test JVM; and integration tests with Testcontainers, which run a real apache/kafka container. Most tests should be broker-less, with a few integration tests per flow.
Q. When would you choose Testcontainers over @EmbeddedKafka?
Answer: When the test should run against the exact broker image used in production, when other real dependencies such as PostgreSQL run in containers too, or when you want to test broker-level behaviour. @EmbeddedKafka needs no Docker and starts quickly inside the JVM, which is enough for most Spring wiring, serialization and error-handler tests.
Intermediate questions
Q. How do you assert the effect of a @KafkaListener when processing happens asynchronously?
Answer: Send the record, then poll for the observable effect with a timeout, for example with Awaitility: await().atMost(10s).untilAsserted(...) on a repository or output topic. Alternatively count down a latch from a test spy. Fixed Thread.sleep calls make tests either flaky or slow, because they guess how long processing takes.
Q. How would you test that a poison record ends up in the dead-letter topic?
Answer: In an integration test, send a record that the listener rejects, then read the dead-letter topic (by default the original name with the -dlt suffix in Spring Kafka 4) with a test consumer created from KafkaTestUtils.consumerProps(...). Assert on the key and the exception headers that DeadLetterPublishingRecoverer adds, such as KafkaHeaders.DLT_EXCEPTION_MESSAGE, and assert that the normal side effect did not happen.
Q. How do you test Kafka Streams windowing logic deterministically?
Answer: With TopologyTestDriver from kafka-streams-test-utils. It runs the topology synchronously without a broker, and TestInputTopic.pipeInput(key, value, timestamp) lets you choose each record’s event time, so windows open and close exactly where the test expects. Results are read from TestOutputTopic, and state stores can be inspected directly.
Tricky and scenario questions
Q. An integration test sends an event right after the context starts, but the listener never receives it, although it works when run on its own later. Why?
Answer: The listener’s group has no committed offset and uses the default auto.offset.reset=latest. If the record is written before the group’s partitions are assigned, the consumer starts after it and never sees it. Set spring.kafka.consumer.auto-offset-reset=earliest for tests, or wait for partition assignment (for example with ContainerTestUtils.waitForAssignment) before sending.
Q. Kafka integration tests pass individually but fail when the whole suite runs. What are the likely causes?
Answer: Shared state: Spring caches the application context, so test classes with the same configuration share one embedded broker, topics and consumer groups. Records left by one test are consumed or counted by another. Use unique keys or topic names per test, assert only on your own data, avoid shared consumer group IDs for test consumers, and do not rely on topics being empty.