'How to mock a constructor which is throwing a IOException with mockito-inline?
How can i mock the next lines:
Workbook templateWorkBook = null;
try {
templateWorkBook = new XSSFWorkbook(templateWithoutEvents);
} catch (IOException ex){
log.error("Error creating workbook from file");
}
I was trying somethig like this but doesn't work.
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);
}
I have the exception when run tests:
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);
Any ideea? Thanks,
Solution 1:[1]
I was trying to find a solution to this problem myself, and using this solution works for my case :
try (MockedConstruction<XSSFWorkbook> mocked =
Mockito.mockConstructionWithAnswer(XSSFWorkbook.class, invocation -> {
throw new IOException();
})) {
Workbook workBook = fileService.generateReport(listItem, startDate, endDate);
}
the constructor itself is not mocked by MockedConstruction, but intercepted. Which explains the error you are getting
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hasarian |