如何使用mockito-inline模拟抛出IOException的构造函数?

Lau*_*lex 2 constructor exception mocking mockito-inline

我如何模拟下一行:

Workbook templateWorkBook = null;
try {
  templateWorkBook = new XSSFWorkbook(templateWithoutEvents);
} catch (IOException ex){
  log.error("Error creating workbook from file");
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试类似的事情,但不起作用。

try (
                MockedConstruction<XSSFWorkbook> mocked = Mockito.mockConstructionWithAnswer(XSSFWorkbook.class, invocation -> null)
                ) {
            doReturn("2021-09-30").when(stpConfigurationMock).getStartDate();
            **when(new XSSFWorkbook()).thenThrow(IOException.class);**
            Workbook workBook = fileService.generateReport(listItem, startDate, endDate);
        }
Run Code Online (Sandbox Code Playgroud)

我在运行测试时遇到异常:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?谢谢,

小智 5

我试图自己找到这个问题的解决方案,并且使用这个解决方案适用于我的情况:

try (MockedConstruction<XSSFWorkbook> mocked = 
Mockito.mockConstructionWithAnswer(XSSFWorkbook.class, invocation -> {
    throw new IOException();
})) {
    Workbook workBook = fileService.generateReport(listItem, startDate, endDate);
}
Run Code Online (Sandbox Code Playgroud)

构造函数本身不会被 MockedConstruction 模拟,而是被拦截。这解释了您收到的错误