简体   繁体   English

Mockito:抛出指定的已检查异常时,“已检查异常对此方法无效”

[英]Mockito: “Checked exception is invalid for this method” when throwing specified checked exception

There are several questions around this on StackOverflow, but I believe this case to be different. StackOverflow 上有几个关于此的问题,但我相信这种情况会有所不同。 I'm using Java 11 and Mockito 2.11.0.我正在使用 Java 11 和 Mockito 2.11.0。

Here's a minimal JUnit 4 test case demonstrating my problem:这是一个最小的 JUnit 4 测试用例,展示了我的问题:

@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 .我是 mocking Jackson 的 ObjectMapper 的readValue(String content, Class<T> valueType)方法的行为- 此处的文档-文档显示该方法可以抛出IOException So why does Mockito report that it is invalid for me to mock throwing such an exception?那么为什么 Mockito 报告我模拟抛出这样的异常是无效的呢?

Interestingly, if I change the behaviour to throw a JsonParseException , which can also be thrown by that method, then Mockito doesn't complain.有趣的是,如果我将行为更改为抛出JsonParseException ,该方法也可以抛出该异常,那么 Mockito 不会抱怨。

Since version 2.10 Jackson removed the IOException, this is the portion of the code:由于版本2.10 Jackson 删除了 IOException,这是代码的一部分:

@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.您在问题中包含的链接指向 jakson-databind 2.7,因此我假设您正在检查错误的文档。

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.原来这是因为我无意中更新了我的jackson版本,并且新版本(2.11.x)不再抛出IOException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM