[Spring Boot] Unit Testing Kafka Producer with Producer Listener

Previously,

[Spring Boot] Unit Testing Kafka Producer with Producer Callback

Introduction

  • Testing can be complicated due to ListenableFuture, ListenableFutureCallback.
  • Even though the functionality is related to Kafka Producer, this callback is handled by Spring Framework rather than spring-kafka.

Let’s look at another option: Producer Listener.

Approach

First of all, it is possible to override ProducerListener bean with our own. If there is no bean provided for ProducerListener, it will set up LoggingProducerListener by default.

KafkaAutoConfiguration.java

Secondly, KafkaTemplate bean will be created using our custom ProducerListener bean. Of course, if you are customizing KafkaTemplate bean, then you would need to add kafkaTemplate.setProducerListener(kafkaProducerListener) in your bean initialization.

KafkaAutoConfiguration.java

Implementation

Producer Listener & Configuration

As seen earlier, a bean is required to override the default ProducerListener.

Unit Test

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store