Home > Software design >  Unit testing object mapper method
Unit testing object mapper method

Time:10-05

I was told that I should unit test this method but I'm not sure how? How would I unit test a method that only maps a JSON string to a DTO. The String line I will get from a Kafka topic through a Kafkalistener.

    public void Mapper(String line) {

    try {
        LeadTimeDTO leadTimeDTO = objectMapper.readValue(line, LeadTimeDTO.class);
        
        System.out.println("leadTimeDTO:"   leadTimeDTO);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException("Error parsing to DTO");

    }

}

CodePudding user response:

Using JUnit5:

I would start by checking that objectMapper.readValue doesn't throw any exception:

assertDoesNotThrow(() -> objectMapper.readValue(line, LeadTimeDTO.class));

Then, check mapped object is not null:

assertThat(leadTimeDTO).isNotNul();

After that, you can check the fields are being populated correctly by using

assertThat(leadTimeDTO.getName()).isEqualTo("Some name");
  • Related