Verfiy/Test Acknowledgment was called in spring boot kafka

Viewed 1060

I've written integration tests for my Spring Boot Kafka (Consumer/Producer) service everything gone well. So I'm committing the offsets of my consumer manually after some processing. I want to verify whether acknowledgment.acknowledge() was called in the consumer. Is is to possible verify?

Here is my method signature of the service:

@KafkaListener(topics = {TOPIC_XXX_V1}, containerFactory = "XXXListener")
    private void consumer(@Payload XXXXRequestEvent xxxxRequestEvent, Acknowledgment acknowledgment) {

.....
// do something with the database

acknowledgment.acknowledge()

For the testing side I'm using @SpyBean for the Service and a MockBean for the database interaction. I want verify somehow whether in the test case the .acknowledge() was called. FYI: the .acknowledge() is a public abstract void method

1 Answers

As the Acknowledge instance is injected and created as part of Spring Kafka when consuming a message, I guess there is no way to use something like verify() of Mockito for this.

When writing a unit test instead you could pass a mocked version of Acknowledge here and then verify that this method was invoked. However, with a unit test, you can't test the actual consumption of a message (serialization, correct message handler, etc.).

So in your case, I would try to verify that your message was acknowledged by e.g. using Testcontainers to execute commands inside the Kafka container and ensuring that the already acknowledged message is not returned any more.

Another approach could be to create a Kafka client as part of your test and then try to consume messages from the same topic for X seconds and expect zero results. Awaitility might help you here.

Related