Skip to content
Kafka Is FunProgress

SpringSpring Kafka Testing

How do you test Kafka listeners in Spring Boot?

Reference answer

Use @EmbeddedKafka (from spring-kafka-test) for integration tests: @SpringBootTest + @EmbeddedKafka(partitions=1, topics={'my-topic'}). Inject KafkaTemplate to produce test messages. Use CountDownLatch or Awaitility to wait for async listener invocations. For unit tests, mock KafkaTemplate with @MockBean. Use EmbeddedKafkaBroker to access the embedded broker URL: @Autowired EmbeddedKafkaBroker broker. Set spring.kafka.bootstrap-servers: ${spring.embedded.kafka.brokers} to connect to embedded broker.

Expected key concepts: @EmbeddedKafka, spring-kafka-test, @SpringBootTest, CountDownLatch, Awaitility, @MockBean, EmbeddedKafkaBroker, spring.embedded.kafka.brokers, integration tests, unit tests