Bad form for JUnit test to throw exception?

Actually, the old style of exception testing is to wrap a try block around the code that throws the exception and then add a fail() statement at the end of the try block. Something like this:

public void testNullParameter() {
    try {
        IPAddress addr = new IPAddress(null);
        fail("InvalidIPAddressException not thrown.");
    } catch(InvalidIPAddressException e) {
        assertNotNull(e.getMessage());
    }
}

This isn’t much different from what you wrote but:

  1. Your assertTrue(addr.getOctets() == null); is useless.
  2. The intend and the syntax are clearer IMO and thus easier to read.

Still, this is a bit ugly. But this is where JUnit 4 comes to the rescue as exception testing is one of the biggest improvements in JUnit 4. With JUnit 4, you can now write your test like this:

@Test (expected=InvalidIPAddressException.class) 
public void testNullParameter() throws InvalidIPAddressException {
    IPAddress addr = new IPAddress(null);
}

Nice, isn’t it?

Now, regarding the real question, if I don’t expect an exception to be thrown, I’d definitely go for way #1 (because it’s less verbose) and let JUnit handle the exception and fail the test as expected.

Leave a Comment