JUnit: Testing for an exception of certain type

exception, java, junit, unit-testing

Solution

Note: I think @Matthew's answer is superior.

You can use the following structure - it tests that the correct exception was thrown (`TestException.class`) and that the message is as expected.

@Test(expected = TestException.class)
public void test_function_negative() {
    try {
        function(-5);
    } catch (TestException ex) {
        assertEquals("Integer may not be negative..", ex.getMessage());
        throw ex;
    }
}

EDIT Why I rethrow the exception (following a comment): the first test below passes while the second does not. So it adds an extra layer of validation. Now If I caught ExceptionB in the code below, both tests would fail.

@Test
public void test1() throws ExceptionB {
    try {
        throw new ExceptionA();
    } catch (ExceptionA e) {
        assertEquals("message", e.getMessage());
    }
}

@Test(expected=ExceptionB.class)
public void test2() throws ExceptionA {
    try {
        throw new ExceptionA();
    } catch (ExceptionA e) {
        assertEquals("message", e.getMessage());
        throw e;
    }
}

public class ExceptionA extends Exception{
    @Override
    public String getMessage() {
        return "message";
    }
}
public class ExceptionB extends ExceptionA{}

Problem

I am wanting to know if I can test (using JUnit) that a specific message generated by an exception gets thrown rather than just "whether or not" an exception was thrown. For example the JunitTest.java code will actually pass the test because an exception was thrown but if I also wanted to test that the string generated by the exception was equal to: "Test Exception: Integer may not be negative.." is this possible? TestException.java ``` public class TestException extends Exception { /** * @param message informative message about the problem found */ public TestException (String message) { super("Test Exception: " + message); } } ``` Test.java ``` public void function(Integer mustBePositive) throws TestException { if (mustBePositive < 0) { throw new TestException("Integer may not be negative.."); } else { mustBePositive = myNum } } ``` JunitTest.java ``` import org.junit.*; public class JUnitTest { @Test(expected = TestException.class) public void functionTest() throws TestException { function(-1); } } ```

Original source

Related problems