Interview Questions

How Create a Test Fixture to Be Shared by All Tests in a Test Class?

JUnit Questions and Answers


(Continued from previous question...)

How Create a Test Fixture to Be Shared by All Tests in a Test Class?

If all tests in a test class needs the same test fixture, you should create a shared test fixture by:

  • Declared private instance variables to register objects used in the test fixture.
  • Create an initialization method with the JUnit "@Before" annotation to create and initiate objects used in the test fixture.

Here is an example test class that uses a common test fixture:

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

// by FYICenter.com
public class GregorianCalendarTest2 {

 // 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);
 }
 
 // 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 "@Before" method before calling each "@Test" method. In our example, the test runner will those methods in this order:

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

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

(Continued on next question...)

Other Interview Questions