如何通过mockito内联模拟抛出IOException的构造函数



我如何模拟下一行:

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

我试过这样的方法,但没用。

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);
}

运行测试时我有一个例外:

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);

有什么想法吗?谢谢,

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

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

构造函数本身并没有被MockedConstruction嘲笑,而是被拦截了。这解释了你得到的错误

最新更新