上下文: 我们正在使用 Junit 5、Spring-Boot 2.6.3 Spring-Boot 附带了对mockito-core 的依赖
问题
我正在寻找为静态方法创建一个模拟。Mockito 提供了一个库(mockito-inline),允许模拟静态方法,但是,当mockito-core 不直接依赖时它可以工作。Mockito-inline 在需要时下载兼容的mockito-core。
(参考:https ://frontbackend.com/java/how-to-mock-static-methods-with-mockito )
可能的解决方案
我如何模拟下一行:
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)
有什么想法吗?谢谢,