How to create a test for DeadLetter Kafka

Viewed 580

In my little microservice, I created a Producer Kafka to send the messages with errors (messages having errors in the JSON format) inside the DeadLetter in this way :

@Component
public class KafkaProducer {
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    public void sendDeadLetter(String message) {
        kafkaTemplate.send("DeadLetter", message);
    }
}

I would like to create a JUnitTest for the completeness of the project, but I have no idea how to create the eventuality of a possible JSON error in order to create the test. I thank everyone for any possible help and advice

2 Answers

To create a JUnitTest consistent with your code. I should recreate the case where you pass it a warped or invalid JSON. In your case, I would opt to configure a MockConsumer from which to read any message that the logic of your code will be invited to the dead letter. To have a usable test structure, I recommend something like this:

@KafkaListener(topics = "yourTopic")
public void listen(String message) {
messages.add(message);
}

For testing a basic structure could be

@Test
 public void testDeadLetter(){

//Set up a mockConsumer
MockConsumer<String,String> yourMockConsumer = new MockConsumer<String,String>   (OffsetResetStrategy.EARLIEST);
yourMockConsumer.subscribe(Collections.singletonList("yourTopic"));

//Sending message on embedded Kafka broker
String error = "ERRORE";
kafkaTemplate.send("yourTopic", error);
//Reading the message may take a second
Thread.sleep(1000);
//Create an Assert that checks you that the message is equal to the error specified           above
 }

I hope it will be useful to you!

Related