How to mock a constructor which is throwing a IOException with mockito-inline?

3.9k Views Asked by At

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,

1

There are 1 best solutions below

2
On

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