Wednesday, May 28, 2008

Unit testing exceptions

When unit testing exceptions, be sure to test for the exceptions that you expect.

I spent nearly an hour rewriting tests to test for what they said they tested.

Here's an example of a bad test.

Exception ex;
// configure mocks
try {
// call test
fail();
} catch(Exception e) {
ex = e;
}
assertNotNull(ex);


Any and all errors that are thrown, including "the mocks are not configured properly" is considered a successful test pass, instead use.



Exception ex;
// configure mocks
try {
// call test
fail();
} catch(Exception e) {
ex = e;
}
assertEquals("the error message I expect.", ex.getMessage() );

1 comment:

Unit test exception strategies said...

Well there is a different way using the framework provided syntax.

Evaluation of unit test exception catching strategies