[SOLVED] How to test if an exception was thrown?


This Content is from Stack Overflow. Question asked by Amikuto

My code:

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

Test class:

TestType testType = TestType.main;
CSVUtil csvUtil = spy(new CSVUtil()); //or CSVUtil csvUtil = mock(CSVUtil.class);
when(csvUtil.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 {
    TagService tagService = new TagServiceImpl(tagDao);
    List<Tag> actualTagList = tagService.findAllTags();
    assertEquals(actualTagList, expectedTagList);
} catch (DaoException | ServiceException 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.

This Question was asked in StackOverflow by Amikuto and Answered by Mishamba It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?