how to handle exceptions in junit

An unexpected exception is a test failure, so you neither need nor want to catch one.

@Test
public void canConvertStringsToDecimals() {
    String str = "1.234";
    Assert.assertEquals(1.234, service.convert(str), 1.0e-4);
}

Until service does not throw an IllegalArgumentException because str has a decimal point in it, that will be a simple test failure.

An expected exception should be handled by the optional expected argument of @Test.

@Test(expected=NullPointerException.class)
public void cannotConvertNulls() {
    service.convert(null);
}

If the programmer was lazy and threw Exception, or if he had service return 0.0, the test will fail. Only an NPE will succeed. Note that subclasses of the expected exception also work. That’s rare for NPEs, but common with IOExceptions and SQLExceptions.

In the rare case that you want to test for a specific exception message, you use the newish ExpectedException JUnit @Rule.

@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void messageIncludesErrantTemperature() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("-400"); // Tests that the message contains -400.
    temperatureGauge.setTemperature(-400);
}

Now, unless the setTemperature throws an IAE and the message contains the temperature the user was trying to set, the test fails. This rule can be used in more sophisticated ways.


Your example can best be handled by:

private void testNumber(String word, int number)
        throws OutOfRangeNumberException {
    assertEquals(word,  service.convert(number));
}

@Test
public final void testZero()
        throws OutOfRangeNumberException {
    testNumber("zero", 0);
}

You can inline testNumber; now, it does not help much. You can turn this into a parametrized test class.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)