Mittwoch, 23. Mai 2012

JUnit - Testing for excepted exceptions

Testing for excepted exceptions is a commen use case. In JUnit 4 there is a nice possibilities to do this:
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void throwsNullPointerExceptionWithMessage() {
    thrown.expect(NullPointerException.class);
    thrown.expectMessage("Exception Message"); 
    // test code goes here
}
The rule just has to be defined once, and then can be reused wherever wanted. The expectMessage function just makes a substring search, so you do not need to have to provide the complete error message.

In JUnit < 4, the testing is more complex:
@Test
public void throwsNullPointerExceptionWithMessage() {
    boolean exceptionThrown = false;
    try {
        // test code goes here
    } catch (Exception e) {
        exceptionThrown = true;
        Assert.assertEquals("Not expected exection type", NullPointerException.class, e.getClass());
        Assert.assertTrue("Not expected error message", e.getMessage().contains("Exception Message")); 
    }
    Assert.assertTrue("Expected exception not thrown", exceptionThrown);
}

Keine Kommentare:

Kommentar veröffentlichen