Gherhard Froehlich was wondering if there was a better way to do positive JUnit exception testing than something like this:
public void testAddService() {
try {
setUp();
TRACER.trace("--- Testing addService() ---");
ssgConnectorProvisioning.addService(serviceData);
TRACER.trace("--- End of test ---", "\n");
} catch (Exception e) {
if(e instanceof SSGConnectorException) {
TRACER.exception("Test OK, because Exception was controlled", e);
} else {
TRACER.exception(e);
fail(e.getMessage());
}
}
}There is, the thing to do is to take advantage of the fact that java will only use one exception block, and it will match the first one that is an assignable class of the exception, so you could do this...
public void testAddService() {
try {
setUp();
TRACER.trace("--- Testing addService() ---");
ssgConnectorProvisioning.addService(serviceData);
TRACER.trace("--- End of test ---", "\n");
} catch (SSGConnectorException sce) {
TRACER.exception("Test OK, because Exception was controlled", e);
} catch (Exception e) {
TRACER.exception(e);
fail(e.getMessage());
}
}
Let's hope he get's this via a Moveable Type pingback. (I've wanted to see if I have it working or not).
Update: I was kind of myoptic when I looked at the post Gherhard had and realized it was missing something this morning. Charles Miller also noticed it last night: the test should fail if no exception is thrown. steve tried to trim it down to a single catch:
public void testAddService() throws Exception{
try {
TRACER.trace("--- Testing addService() ---");
ssgConnectorProvisioning.addService(serviceData);
TRACER.trace("--- End of test ---", "\n");
} catch (SSGConnectorException sce) {
TRACER.exception("Test OK, because Exception was controlled", e);
}
fail("We expected a SSGConnectorException");
}
Except in this case the test will fail if the exception is throw! (a false failure). And this also assumes SSGConnectiorException is the only exception thrown. If your tests are written so that only one test is done per test method (a good practice IMHO) you could fix this by putting a return statement in the catch block or moving the fail inside of the try block. Otherwise (such as cases where the exception is just a set up for the real test) you will need two fail statements or catch statements or continue the test in the catch block. |