4.7 One-Time Set Up and Tear Down

4.7.1 Problem

You want to run some setup code one time and then run several tests. You only want to run your cleanup code after all of the tests are finished.

4.7.2 Solution

Use the junit.extensions.TestSetup class.

4.7.3 Discussion

As outlined in Recipe 4.6, JUnit calls setUp( ) before each test, and tearDown( ) after each test. In some cases you might want to call a special setup method once before a series of tests, and then call a teardown method once after all tests are complete. The junit.extensions.TestSetup class supports this requirement. Example 4-4 shows how to use this technique.

Example 4-4. One-time set up and tear down
package com.oreilly.javaxp.junit;

import com.oreilly.javaxp.common.Person;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class TestPerson extends TestCase {

    public void testGetFullName(  ) { ... }

    public void testNullsInName(  ) { ... }

    public static Test suite(  ) {
        TestSetup setup = new TestSetup(new TestSuite(TestPerson.class)) {
            protected void setUp(  ) throws Exception {
                // do your one-time setup here!
            }

            protected void tearDown(  ) throws Exception {
                // do your one-time tear down here!
            }
        };
        return setup;
    }
}

TestSetup is a subclass of junit.extensions.TestDecorator, which is a base class for defining custom tests. The main reason for extending TestDecorator is to gain the ability to execute code before or after a test is run.[4] The setUp( ) and tearDown( ) methods of TestSetup are called before and after whatever Test is passed to its constructor. In our example we pass a TestSuite to the TestSetup constructor:

[4] JUnit includes source code. Check out the code for TestSetup to learn how to create your own extension of TestDecorator.

TestSetup setup = new TestSetup(new TestSuite(TestPerson.class)) {

This means that TestSetup's setUp( ) method is called once before the entire suite, and tearDown( ) is called once afterwards. It is important to note that the setUp( ) and tearDown( ) methods within TestPerson are still executed before and after each individual unit test method within TestPerson.

4.7.4 See Also

Recipe 4.6 describes setUp( ) and tearDown( ).