Interview Questions

Can You Create Tests without Using a Common Test Fixture?

JUnit Questions and Answers


(Continued from previous question...)

Can You Create Tests without Using a Common Test Fixture?

Of course, the answer to this question is YES. Here is a example:

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

// by FYICenter.com
public class GregorianCalendarTest1 {

 // testing roll(Calendar.DAY, true) method
 @Test public void nextDayNewYear() {

  // creating the test fixture
  GregorianCalendar cal = new GregorianCalendar();
  cal.set(2008, 12, 31, 23, 59, 59);
  
  // testing starts
  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() {

  // creating the test fixture
  GregorianCalendar cal = new GregorianCalendar();
  cal.set(2008, 12, 31, 23, 59, 59);
  
  // testing starts
  cal.roll(Calendar.DAY_OF_MONTH, true);
  Assert.assertEquals("Next day of 31-Dec-2008 is January",
     0, cal.get(Calendar.MONTH));
  }
}

Obviously, two tests in this test class are using the same test fixture. It should be moved out of the test methods. See the next question.

(Continued on next question...)

Other Interview Questions