I'm working on a SpringBoot application that must process messages sent via Kafka. In the application, I have a Spring Bean with methods annotated with @KafkaListener
. These methods get called when a message is read from the appropriate topic and call a business logic to perform actual processing.
Now I'd like to create a test for this using the lib "spring-kafka-test", i.e. embedded kafka. I've created a test that sends a message to the topic and then checks whether the business logic has been called. The logic is mocked via @MockBean
.
My test class looks like this:
@SpringBootTest
@DirtiesContext
@EmbeddedKafka(
topics = { "myTopic" },
brokerProperties = { "listeners=PLAINTEXT://localhost:9092" } // <-- Why is this needed?
)
class KafkaListenerDispatchingTest {
/** Object for sending the test messages */
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@MockBean
private BusinessLogic businessLogic;
@Test
public void testProcessing() throws Exception {
var testMessage = "...";
kafkaTemplate.send("myTopic", testMessage).get();
Mockito.verify(businessLogic).myMethod();
}
}
Without the line marked with "Why is this needed" the test does not work. In the console I see many lines with
[Producer clientId=producer-1] Connection to node -1 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.
With the marked line the test works OK.
My question is: Why is the broker property listeners
needed? From the Spring class (EmbeddedKafka
) I'd expect that everything works with the default values and that special values only must be specified when having special needs.
I have
- spring-boot 2.7.13
- spring-kafka 2.9.9
- spring-kafka-test 2.9.9