Torn tearDown
I frequently encounter two problems with JUnit’s tearDown:
1. tearDown is not executed if setUp fails, leading to resource leaks.
2. Mock verification calls in tearDown can obfuscate original causes of test failures.
Many developers work around the mock verification problem by commenting out the verification to expose the original problem. The problem with this is that it’s very easy to forget to uncomment the verification calls, hiding future test failures. Another alternative is to blatently violate the DRY principle.
My solution to these problems is to introduce a custom TestCase that overrides runBare, the skeleton directing the steps performed in a test:
public void runBare() throws Throwable {
try {
setup();
runTest();
tearDownExpectations();
} finally {
tearDown();
}
}
tearDown can now do its thing if setUp fails and tearDownExpectations (a Template Method containing Mock object expectation verification calls) will only be performed if the test method is successful.
