0

I am trying to cover a Unit test case for an Exception. my code looks like this

if (null != csvWriter) {
        try {
          csvWriter.close();
        } catch (Exception ee) {
          log.error("Error in closing csvWriter. You may loose content.");
        }
      }

I want to cover the exception in Mockito unit case. Is there a way?

kisame
  • 11
  • 5

1 Answers1

0

Suppose your CSVWriter is a fake. Then you could make it throw an exception on calling the close method.

@Test
void csvWriterThrows() throws IOException
{
    final CSVWriter csvWriter = Mockito.mock(CSVWriter.class);
    Mockito.doThrow(IOException.class).when(csvWriter).close();

    final IOException ioException = Assertions.assertThrows(IOException.class, csvWriter::close);

    Assertions.assertEquals(IOException.class, ioException.getClass());
    # more assertions...
}
Valerij Dobler
  • 1,848
  • 15
  • 25