0

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

Elenora
  • 1
  • 4

1 Answers1

0

You seem to have some misunderstanding.

producer.send

consumer.poll

You are calling the kafka-clients directly and are not using Spring at all in this test.

ListenerExecutionFailedException is an exception that Spring's listener container wraps user exceptions thrown by message listeners.

Community
  • 1
  • 1
Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • How exactly do you use Spring to send and receive test messages so that @KafkaListener methods from your app are called and catch their exceptions if thrown? fyi i've changed the expected exceptions to runtime and throwable, also sending the messages using kafkatemplate – Elenora Mar 24 '20 at 04:58
  • The listener runs in a different thread. If you want to catch the exception in your unit test, you must call the listener directly from your test instead of sending a message to kafka. If you want to create an integration test, you can wrap your listener - see [this answer](the listener runs in a different thread) for an example. – Gary Russell Mar 24 '20 at 13:37