Interview Questions

Can You Write a JUnit Test Suite in 2 Minutes?

JUnit Questions and Answers


(Continued from previous question...)

Can You Write a JUnit Test Suite in 2 Minutes?

The quickest way to write a test suite class is to:

   1. Define a "public static Test suite()" method
      Create an empty TestSuite object
      Add test case classes using the addTestSuite() method
   2. Define a "public static void main()" method to run tests.
      Call "junit.textui.TestRunner.run()" to run all tests.
      TestRunner.run() will call the "suite()" method.
         And run all tests in all test cases in the test suite.

Here is a nice example provided in the article "Writing a JUnit Test in 5 minutes" by Kamal Mettananda with some minor changes. This sample class only works with JUnit 3.8.

package com.parcelhouse.myproj;

import junit.framework.Test;
import junit.framework.TestSuite;

public class CalcTestSuite {
     public static void main(String[] args) {
          junit.textui.TestRunner.run(CalcTestSuite.class);
          //junit.swingui.TestRunner.run(CalcTestSuite.class);
          //junit.awtui.TestRunner.run(CalcTestSuite.class);
     }
     public static Test suite() {
          TestSuite suite 
             = new TestSuite("Test for com.parcelhouse.myproj");

          suite.addTestSuite(CalcTest.class);
          //suite.addTestSuite(ComputerTest.class);
          //add more test case classes here

          return suite;
     }
}

(Continued on next question...)

Other Interview Questions