4

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

Alexander
  • 2,925
  • 3
  • 33
  • 36
Jacket
  • 353
  • 6
  • 18
  • 1
    Hi michalk, could you show me an example structure for the simple "send" test in this case? If you could kindly answer my question so that I can then accept the answer to you – Jacket Feb 28 '21 at 17:25
  • 2
    https://github.com/ConsenSysMesh/kafka-deadletter/tree/master/src/test – aran Mar 02 '21 at 12:56
  • Hi aran,I saw your link but I was unable to adapt the tests to my deadLetter above, also due to my inexperience, could you help me in structuring a test to see the correct reception of the message? If you could answer me as an answer and not a comment I can mark you as the correct answer – Jacket Mar 03 '21 at 08:42
  • @aran I just need a test on the correct reception of the message – Jacket Mar 03 '21 at 08:43

2 Answers2

3

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!

Numero 21
  • 245
  • 5
  • 17
2

You can create Kafka topic using testcontainers and write your tests on top of that.

Sharing an example on how to use testcontainers https://github.com/0001vrn/testcontainers-example

Varun Thakur
  • 214
  • 1
  • 6