Wednesday, September 19, 2012

Junit setUp and tearDown

When you have several test cases, and noticed that the setUp and tearDown are run for each test case. You use TestSuite to run all test cases at once, but since all test cases are based on the same setUp code, you might might like to make setUp run only once, instead of each time a test case is called.

What say?

With JUnit 4, we can use the annotation called @BeforeClass for setUp method and @AfterClass for the tearDown method. For those who are still compel to use the earlier version of JUnit, here is the trick.


Wrapped the setUp and tearDown method in the Suite. For example, the code below is the case if you want to run a single setUp and tearDown for all your test methods in YourTestClass testcase.

public static Test suite() {
  return new TestSetup(new TestSuite(YourTestClass.class)) {
  protected void setUp() throws Exception {
    System.out.println(" Global setUp ");
  }
  protected void tearDown() throws Exception {
    System.out.println(" Global tearDown ");
  }
  };
}
Please be aware that by tweaking the architecture of Junit, we are violating the clean code concept. It says, each testcase is atomic and independent and the set-up and tear-down should be applied to each. On the performance aspect, the Junit philosophy is still valid as it has to do with tests and not productions.