Skip to content
Kafka Is Fun

SpringSpring Kafka Testing

How do you test Kafka listeners in Spring Boot?

Reference answer

Use @EmbeddedKafka from spring-kafka-test (with Spring Boot, the spring-boot-starter-kafka-test starter) for integration tests: @SpringBootTest plus @EmbeddedKafka(partitions = 1, topics = {"my-topic"}). The embedded broker runs in KRaft mode (Kafka 4.0 removed ZooKeeper) and sets the system property spring.embedded.kafka.brokers; the bootstrapServersProperty of @EmbeddedKafka defaults to spring.kafka.bootstrap-servers, or you can set spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}. Inject KafkaTemplate to send test messages, and EmbeddedKafkaBroker if you need the broker itself. The listener runs asynchronously, so the test must wait for it, for example with a CountDownLatch, a BlockingQueue with a timed poll (as in the Spring Kafka docs), or Awaitility. Using a different topic for each test avoids cross-talk. For tests without a broker, mock collaborators with @MockitoBean (Spring Boot's reference documents @MockitoBean and @MockitoSpyBean for this) or use the MockConsumerFactory and MockProducerFactory provided since 3.0.7.

Expected key concepts: @EmbeddedKafka, spring-kafka-test, @SpringBootTest, CountDownLatch, Awaitility, @MockitoBean, EmbeddedKafkaBroker, spring.embedded.kafka.brokers, MockConsumerFactory, KafkaTemplate

How did that feel?

Your own verdict, not the score. It shows up next to this question in the list, so you can come back to the shaky ones.