One-Time Set Up and Tear Down
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.
Solution
Use the junit.extensions.TestSetup class.
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.[21] The setUp( ) and tearDown( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access