Interview Questions

Can You Write a JUnit Test Case Class in 2 Minutes?

JUnit Questions and Answers


(Continued from previous question...)

Can You Write a JUnit Test Case Class in 2 Minutes?

With the simple class, Calc.java, listed in the previous question, you should be able to write a simple JUnit test case class within 2 minutess. 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.TestCase;
import com.parcelhouse.myproj.Calc; //testing class

public class CalcTest extends TestCase {
     Calc c = null;
     public CalcTest(String name) {
          super(name);
     }

     protected void setUp() throws Exception {
          super.setUp();
          c = new Calc();
     }

/*
* Test method for 'Calc.add(int, int)'
*/
     public void testAdd() {
          int x = c.add(5,6);
          assertEquals(11, x);
     }

/*
* Test method for 'Calc.multiply(int, int)'
*/
     public void testMultiply() {
          int x = c.multiply(5,6);
          assertEquals(30, x);
          }

     public static void main(String[] args) {
          junit.textui.TestRunner.run(CalcTest.class);
     }
}

This test case class contains two tests:

  • "testAdd()" - Testing the Calc.add() method. It will fail, because of the error in the Calc.java.
  • "testMultiply()" - Testing the Calc.multiply() method. It will pass.

This test case class also contains the main() method that allows to run both tests by: "java CalcTest". The line junit.textui.TestRunner.run(CalcTest.class) is where the trick occurs. The TestRunner runs all the methods in the CalcTest class which has testXXX() signature using reflection.

(Continued on next question...)

Other Interview Questions