Test-wide Setup and Tear Down of JUnit Tests
Thursday, August 17th, 2006JUnit 4.0 introduces the @BeforeClass annotation, providing a way to run a class-wide setup method before any of the tests in that class are run. The analogous @AfterClass annotation allows for tear down of those fixtures. I work on a project that hasn’t yet upgraded to JUnit 4.0, and although less widely publicized, it is possible to accomplish the same thing with 3.8.x.
Think before doing this. Tests should be independent of one another. If your tests share fixtures, side effects from one test could affect the results of others. Sometimes, however, a test fixture is just too expensive to set up and tear down with every test. In my case, I needed to set up a database and import a substantial quantity of data. Doing this for every test would’ve made the suite prohibitively slow.
(more…)
