1

I have a spring component with @KafkaListener method:

@Slf4j
@Component
public class ResponseHandler {

    private final ResponseMessageService responseMessageService;

    public ResponseHandler(ResponseMessageService responseMessageService) {
        this.responseMessageService= responseMessageService;
    }

    @KafkaListener(topics = "response-topic", groupId = "response-group")
    public void listen(ResponseMessage responseMessage) {
        responseMessageService.processResponse(responseMessage);
    }
}

Now, I want to test this method. I want to make sure that this method receives messages correct. I try to create a Unit test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ResponseHandlerTest {

    @ClassRule
    public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1, false, 5, "response-topic");

    @BeforeClass
    public static void setup() {
        System.setProperty("spring.kafka.bootstrap-servers", broker.getEmbeddedKafka().getBrokersAsString());
    }

    @Test
    public void listen() {
    }
}

But I don't understand what next. how can I test this method?

ip696
  • 6,574
  • 12
  • 65
  • 128
  • Possible duplicate of [How to write Unit test for @KafkaListener?](https://stackoverflow.com/questions/52783066/how-to-write-unit-test-for-kafkalistener) – eis Apr 15 '19 at 13:26

1 Answers1

1

See this answer for one way to do it.

Also, read Artem Bilan's answer on that same question.

Finally, you can replace your ResponseMessageService with a mock object in your test case, and verify it was called as expected.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179