Mockito: "Checked exception is invalid for this method" when throwing specified checked exception

Viewed 1220

There are several questions around this on StackOverflow, but I believe this case to be different. I'm using Java 11 and Mockito 2.11.0.

Here's a minimal JUnit 4 test case demonstrating my problem:

@Test
public void shouldAllowMocking() throws Exception {
  ObjectMapper objectMapper = mock(ObjectMapper.class);
  when(objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new IOException("the-message"));
}

I'm mocking the behaviour of Jackson's ObjectMapper's readValue(String content, Class<T> valueType) method - documentation here - and the documentation shows that that method can throw an IOException. So why does Mockito report that it is invalid for me to mock throwing such an exception?

Interestingly, if I change the behaviour to throw a JsonParseException, which can also be thrown by that method, then Mockito doesn't complain.

2 Answers

Since version 2.10 Jackson removed the IOException, this is the portion of the code:

@SuppressWarnings("unchecked")
public <T> T readValue(String content, JavaType valueType)
    throws JsonProcessingException, JsonMappingException
{
    _assertNotNull("content", content);
    try { // since 2.10 remove "impossible" IOException as per [databind#1675]
        return (T) _readMapAndClose(_jsonFactory.createParser(content), valueType);
    } catch (JsonProcessingException e) {
        throw e;
    } catch (IOException e) { // shouldn't really happen but being declared need to
        throw JsonMappingException.fromUnexpectedIOE(e);
    }
} 

The link you included in the question points to the jakson-databind 2.7 so I assume you are checking the wrong doc.

This turns out to be because I'd unintentionally updated my jackson version as well, and the newer versions (2.11.x) don't throw IOException any more.

Related