I am trying to write a Java unit test using Mockito but am having trouble to get a matcher to work.
I want to test the following class
CustomService.java
public class CustomService {
private final ApplicationProperties props;
public CustomService(ApplicationProperties props){
this.props = props;
}
private final ObjectMapper mapper = new ObjectMapper();
public void method(JsonNode message) throws CustomException {
try {
List<String> actions = mapper.readValue(message.get("actions").toString(), mapper.getTypeFactory().constructCollectionType(List.class, String.class));
System.out.println(actions);
} catch (IOException ex){
throw new CustomException(ex);
}
}
}
I have a CustomException class
CustomExcepton.java
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class CustomException extends Exception {
public CustomException(Throwable cause) {
super(cause);
}
}
I want to test that the CustomException is thrown. I am using Mockito. I have tried the below but the given statement doesn't seem to pick up the (readValue) line of code in the method
CustomServiceTest.java
public class CustomServiceTest {
private final ApplicationProperties props = mock(ApplicationProperties.class);
private final CustomService customService = new CustomService(props);
private static final ObjectMapper objectMapper = new ObjectMapper();
@Test
public void CustomExceptionIsThrown() throws Exception {
ObjectMapper mapper = mock(ObjectMapper.class);
given(mapper.readValue(anyString(), any(TypeReference.class))).willThrow(new IOException("This is a test"));
String json = "{\"actions\":[\"ac1\",\"ac2\",\"ac3\",\"ac4\"]}";
JsonNode d = objectMapper.readTree(json);
assertThrows(CustomException.class, () ->
customService.method(d));
}
}
I get the following error when I run the test
Expected exception.CustomException to be thrown, but nothing was thrown..
Help would be appreciated.
I also met this same problem, and i find that although i mock objectMapper like " when(objectMapper.readValue(anyString(), any(TypeReference.class))).thenReturn(xxxx);" but when i invoke the test, the first param of readValue(xx,xx) is null which should be a String object. So, you might want to check readValue method input param again.Hope it will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With