0

I have this class with this void method that maps a JSON string to a DTO:

public class OBTMapper {

public void Mapper(String line){

    final ObjectMapper objectMapper = new ObjectMapper();
    final DTO dto;
    try {
        dto = objectMapper.readValue(line, DTO.class);
        System.out.println(dto);
    } catch (JsonProcessingException e) {

        System.out.println("haha");
        throw new IllegalArgumentException("Error parsing the JSON String");
    }

    }
}

How can I unit test this method to make sure that the method does what it should?

  • 1
    Would write testable code that returns the result string for example. The code that prints whether there's an exception or not can be within another method that wouldn't need thorough testing or could be made testable by writing to any printstream passed in – zapl Oct 03 '22 at 23:03

1 Answers1

2

To answer your general question of "how to unit test a void function", think about the purpose of the void function. It probably exists in order to operate on data which exists within the instance that the method is in. Therefore, you can test a void method by testing it produces the proper side effects on the instance variables it touches.

For your specific case you are looking to test that your program prints specific output to system.out.println(), which you can do be redirecting system.out to a buffer, explained here JUnit test for System.out.println().

Lastly, when you want to mock objects that are called by your void() methods, there are helpful libraries like Mockito which use reflection to overwrite the output of methods.

Ryan
  • 154
  • 4