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.
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.[21] 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:
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
.
Recipe 4.6 describes setUp( )
and tearDown( )
.
[21] JUnit includes
source code. Check out the code for TestSetup
to
learn how to create your own extension of TestDecorator
.
Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.