00:00

Testing Kafka Applications in Spring Boot

Last updated:

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

Test levels for Kafka applicationsA pyramid of three levels. At the bottom, many fast unit tests that test business logic, MockProducer and MockConsumer, and Kafka Streams topologies with TopologyTestDriver, without a broker. In the middle, integration tests with Spring's embedded Kafka broker running inside the test JVM. At the top, a few integration tests against a real apache/kafka container started by Testcontainers, closest to production. Testcontainersreal broker @EmbeddedKafkabroker inside the test JVM Unit tests without a brokerplain logic, MockProducer, MockConsumer, TopologyTestDriver fewer, slower,closest to production many, fast
Most tests should not need a broker; a few integration tests prove that configuration, serialization and listeners work together.
ApproachSpeedWhat it provesWhat it cannot prove
Plain unit tests and MockProducerMillisecondsBusiness logic, which records are sent with which keysSerialization over the network, listener configuration, rebalancing
TopologyTestDriverMillisecondsKafka Streams logic, windows and joins with controlled timestampsReal partitioning and repartition topics on a cluster
@EmbeddedKafkaSecondsSpring wiring, serializers, listeners, error handlers, transactionsBehaviour of a specific broker version or Docker networking
TestcontainersSeconds (container start)Everything above against the same broker image you run in productionMulti-broker failure scenarios, unless you start several containers

2. Dependencies

pom.xml (test dependencies, versions managed by Spring Boot)
<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.

OrderPublisher.java and PaymentListener.java
@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:

ShipmentNotifierTest.java
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:

PaymentFlowEmbeddedTest.java
@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 default latest, 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:

PaymentFlowContainerTest.java
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.

Embedded or container? Embedded Kafka needs no Docker and starts quickly, which suits most Spring wiring tests. Testcontainers is the better choice when you want the exact broker version from production, or when you combine Kafka with other containers such as PostgreSQL in one end-to-end test.

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:

PaymentFlowEmbeddedTest.java (second test)
@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:

ViewCountTopologyTest.java
@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 default auto.offset.reset=latest skips records sent before its partitions were assigned. Use earliest in tests.
  • Thread.sleep as 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.KafkaContainer instead of org.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.

13. References