So I need to create an integration test for my kafkalistener method, where the test expects ListenerExecutionFailedException is actually thrown because the message was failed during consumption due to another service being inactive.
Below is the test code, where I use embeddedkafkabroker for producer and consumer:
@Test(expected = ListenerExecutionFailedException.class)
public void shouldThrowException() {
RecordHeaders recordHeaders = new RecordHeaders();
recordHeaders.add(new RecordHeader("messageType", "bootstrap".getBytes()));
recordHeaders.add(new RecordHeader("userId", "123".getBytes()));
recordHeaders.add(new RecordHeader("applicationId", "1234".getBytes()));
recordHeaders.add(new RecordHeader("correlationId", UUID.randomUUID().toString().getBytes()));
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(
"TEST_TOPIC",
1,
null,
"message",
"",
recordHeaders);
producer.send(producerRecord);
consumer.subscribe(Collections.singleton("TEST_TOPIC"));
consumer.poll(Duration.ofSeconds(2));
}
What I'm wondering is the exception was considered as not thrown and the test fails even though I know the message is indeed received by the listener and the exception was thrown since I saw them on the log.
And even though I changed the expected into Throwable no exception seems to be detected.
What should I do to make the exception to be detected by Junit?
Also, another interesting thing is that I tried to mock the service class which was called in the listener and return some dummy value but the service is not called when I used Mockito.verify