Wednesday, June 25, 2008
Here’s The Wrong Way To Test Exceptions…
byRecently I found myself reading a LiveJournal blog interestingly named Workings of a Twisted Mind. Well, twisted or not, in the past couple of months the author has made several excellent posts regarding best practices in unit testing. My favorite is a recent entry that begins, ”Here’s the wrong way to test exceptions in C++ and Java...”
Testing Anti Pattern: Testing Exceptions
Here’s the wrong way to test exceptions in C++ and Java:
bool gotExcep = false;
try {
callSomethingThatThrows();
} catch (exception &e) {
gotExcep = true;
}
CPPUNIT_ASSERT(gotExcept);Here’s the idiomatic way:
try {
callSomethingThatThrows();
CPPUNIT_FAIL("call something should have thrown an exception!");
} catch (exception &e) {
CPPUNIT_ASSERT(true);
}Why bother with the CPPUNIT_ASSERT(true)? Because it conveys intent. The Exception is the correct path. This idiom comes from JUnit, learn it, use it.
Not only does this demonstrate an excellent grasp of best practices in software testing, but I think the term Testing Anti Pattern is right on. The first example is an incredibly common solution to the problem of testing exceptions. However, the second example does a much better of conveying the intent of the test. It also relocates the failure to the correct spot in the code.
I had never considered applying the concept of anti patterns into unit testing, but it certainly can be. Maybe it is time to start exploring the idea of Testing Anti Patterns a little more closely…