Skip to main content

Global setUp() and tearDown() in JUnit tests

Posted by simongbrown on April 16, 2004 at 2:43 PM PDT

Like many people, I want a way to run some one-time set up and tear down logic and the approach I usually take is to drop some code into a static initializer block in an abstract test case. For example...

public abstract class SomeTestCase extends TestCase {

  static {
    // perform the "global" set up logic
  }

}

Providing that I remember to subclass SomeTestCase then this approach works well. So that's set up covered, but what about tear down? Simple - just use a JVM shutdown hook.

public abstract class SomeTestCase extends TestCase {

  static {
    // perform the "global" set up logic

    // and now register the shutdown hook for tear down logic
    Runtime.getRuntime().addShutdownHook(new SomeTestCaseShutdownHook());
  }

}

This is quite a simple solution and is an alternative to the TestSetup class. As an example, I use it for creating a file structure on disk prior to running some tests and deleting that structure when the tests have run. The only caveat with this solution is that when you run your unit tests through Ant, the Ant ClassLoader executes the static initializer (and resets static variables) more than once. I don't know quite why it does this but if your global set up and tear down logic can safely be run more than once then it's not too much of a problem. Incidentally, this technique runs really well with the IntelliJ JUnit runner.

Related Topics >>