1

I've the following configuration

server:
  port: 8001
spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      auto-offset-reset: latest
      group-id: group-id
      value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
      key-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
      properties:
        spring.deserializer.key.delegate.class: org.apache.kafka.common.serialization.StringDeserializer
        spring.deserializer.value.delegate.class: <package..>.config.kafka.KafkaEventDeserializer
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: <package..>.config.kafka.KafkaEventSerializer
  
kafka:
   topic-name: topic-name
   group-id: group-id

I want to test the following Kafka Consumer

@KafkaListener(topics = "#{'${kafka.topic}'}",
               groupId = "#{'${kafka.group-id}'}")
public void consumeEvents(Event event) throws RuntimeException {
      throw new RuntimeException("EventType does not match !");
}

this is my test case

@Test
@SneakyThrows
void consumeEvents_RuntimeExceptionShouldBeThrown() {
    
    ...
    await().atMost(2, TimeUnit.SECONDS)
           .untilAsserted(() -> assertThrows(RuntimeException.class, () -> kafkaTemplate.send(receiptTopic, "key", event)));
    
}

The exception is thrown by the test failed !

It seems that the excpetion is already catched, thus assertThrows doesn't work properly

How can we handle such case ? Thanks

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Smaillns
  • 2,540
  • 1
  • 28
  • 40
  • 1
    Your producer code isn't shown, and the consumer isn't coupled to it at all, so unclear what you expected to happen. So, this code works fine if you're not throwing an exception inside the KafkaTemplate send method (such as by mocking it) – OneCricketeer Aug 26 '22 at 13:43

1 Answers1

0

You don't need a producer to test this

// TODO: get consumer service instance 
final Event event = new Event();
assertThrows(RuntimeException.class, 
    () -> service.consumeEvents(event));
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • That doesn't respond directly our problem (the exception thrown that's catched -a priori- by the kafka ErrorHandlingDeserializer), Absolutely, we can cover the case in the unit tests – Smaillns Aug 26 '22 at 14:55
  • 1
    I answered the question with the only information given in the question. If you want to test `ErrorHandlingDeserializer`, then you should construct that and call a `deserialize` method, given a byte array, and still not need to use a consumer. – OneCricketeer Aug 26 '22 at 17:25