Interview Questions

How To Destroy a JUnit Test Fixture?

JUnit Questions and Answers


(Continued from previous question...)

How To Destroy a JUnit Test Fixture?

In most cases, you don't need to destroy the test fixture used in a test class. The Java garbage collector will destroy all objects used in the test fixture for you automatically.

But if you want to help the garbage collector, you can:

  • Create an cleanup method with the JUnit "@After" annotation to release all objects used in the test fixture.

Here is an example test class that release the object used in the test fixture with an "@After" method:

import org.junit.*; 
import java.util.*;

// by FYICenter.com
public class GregorianCalendarTest3 {

 // variables for the test fixture
 GregorianCalendar cal = null;

 // initialize the test fixture 
 @Before public void init() {
  cal = new GregorianCalendar();
  cal.set(2008, 12, 31, 23, 59, 59);
 }
 
 // clean up the test fixture
 @After public void cleanup() {
  cal = null;
 }
 
 // testing roll(Calendar.DAY, true) method
 @Test public void nextDayNewYear() {
  cal.roll(Calendar.DAY_OF_MONTH, true);
  Assert.assertEquals("Next day of 31-Dec-2008 is year 2009", 
     2009, cal.get(Calendar.YEAR));
  }

 // testing roll(Calendar.DAY, true) method
 @Test public void nextDayNewMonth() {
  // testing starts
  cal.roll(Calendar.DAY_OF_MONTH, true);
  Assert.assertEquals("Next day of 31-Dec-2008 is January", 
     0, cal.get(Calendar.MONTH));
  }
}

JUnit test runner will automatically run the "@After" method after calling each "@Test" method. In our example, the test runner will those methods in this order:

 @Before public void init()
 @Test public void nextDayNewYear()
 @After public void cleanup()

 @Before public void init()
 @Test public void nextDayNewMonth()
 @After public void cleanup()

Well, the "@After" method is really unnecessary. But if there are external resources created in the test fixture, you must release those resources yourself. See the next question.

(Continued on next question...)

Other Interview Questions