Friday, April 16, 2004

tearDown()

What's the right way to use tearDown() in JUnit tests? I spent an afternoon fixing all the places in our codebase where programmer's had forgotten to call super.setUp() and super.tearDown(), respectively, in their own setUp() and tearDown(). To prevent this in the future, I changed BaseTestCase, our in-house extension of JUnit's TestCase, to catch this in the future when running tests: setUp() and tearDown() in BaseTestCase set flags when run, and I overrode runBare() to check for these flags. Voila!

But Paul Holser, a fellow ThoughtWorker on the project, pointed out that tearDown() should also be recoded. Usually everyone writes:

    protected void tearDown() throws Exception {
        // do your tear down here
        super.tearDown();
    }

But Paul suggests instead:

    protected void tearDown() throws Exception {
        try {
            // do your tear down here
        } finally {
            super.tearDown();
        }
    }

I think Paul is correct, but that means I need to go back and fix up some 50 spots and delay working on functionality. Is it worth the extra work?

No comments: