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?
CodePudding user response:
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.