简体   繁体   中英

How to test if an exception was thrown?

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?

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM