如何模拟构造函数行:
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模拟,而是被拦截。这解释了您遇到的错误