How can I run setUp() and tearDown() code once for all of my tests?
The desire to do this is usually a symptom of excessive coupling in your design. If two or more tests must share the same test fixture state, then the tests may be trying to tell you that the classes under test have some undesirable dependencies. Refactoring the design to further decouple the classes under test and eliminate code duplication is usually a better investment than setting up a shared test fixture. But if you must… You can wrap the test suite containing all your tests in a subclass of TestSetup which invokes setUp() exactly once before all the tests are run and invokes tearDown() exactly once after all the tests have been run. The following is an example suite() method that uses a TestSetup for one-time initialization and cleanup: import junit.framework.*; import junit.extensions.TestSetup; public class AllTestsOneTimeSetup { public static Test suite() { TestSuite suite = new TestSuite(); suite.
The desire to do this is usually a symptom of excessive coupling in your design. If two or more tests must share the same test fixture state, then the tests may be trying to tell you that the classes under test have some undesirable dependencies. Refactoring the design to further decouple the classes under test and eliminate code duplication is usually a better investment than setting up a shared test fixture. But if you must… You can add a @BeforeClass annotation to a method to be run before all the tests in a class, and a @AfterClass annotation to a method to be run after all the tests in a class.