Home > Enterprise >  How to test if an exception was thrown?
How to test if an exception was thrown?

Time:09-19

My code:

public String getTemplate(TestType fileType) {
    Util util = new Util();
    try {
        return util.addPrefix(util.getTemplate(fileType));
    } catch (IOException e) {
        logger.warn(e.getMessage());
        throw new MyException(...);
    } catch (SyntaxException e) {
        logger.warn(e.getMessage());
        throw new MyException(...);
    }
}

Test class:

TestType testType = TestType.main;
Util util = spy(new Util()); //or Util util = mock(Util.class);
when(util.getTemplate(testType)).thenThrow(new SyntaxException(...)); //or IOException

String out = runService.getTemplate(testType);

But it doesn't work. Since this method creates a new class. Is it possible to mock the creation of a new inner class without using PowerMock?

CodePudding user response:

Maybe try using junit and assertThrows function. You can find more info here

Some time ago I wrote this test.

try {
    Mockito.when(tagDao.findAllTags()).thenReturn(expectedTagList);
    TagService tagService = new TagServiceImpl(tagDao);
    List<Tag> actualTagList = tagService.findAllTags();
    assertEquals(actualTagList, expectedTagList);
} catch (DaoException | ServiceException e) {
    fail(e);
}

You can try to change fail(e) to assertEquals or smth else, that will validate your exception.

If you will ask me which approach is better, I will say that the first one is more understandable and easily readable.

CodePudding user response:

You didn't check for any throws in tested code. Your test class only mocks behaviour of "getTemplate()" by calling .thenThrow on:

    csvUtil.getTemplate(testType)

If you want to check if exception is thrown you can use many assertion libraries. For example using junit.jupiter you can perform it by calling:

        assertThatExceptionOfType(YourExceptionClass.class)
                .isThrownBy(() -> csvUtil.getTemplate(testType));

you can additionally (if needed) check if that exception had specific message for example:

        assertThatExceptionOfType(YourExceptionClass.class)
                .isThrownBy(() ->
                       csvUtil.getTemplate(testType)
                ).withMessage("expected message here");
  • Related