Interview Questions

How To Write a Single Class to Define Multiple Tests and Run Them?

JUnit Questions and Answers


(Continued from previous question...)

How To Write a Single Class to Define Multiple Tests and Run Them?

Here is the answer for JUnit 3.8:

   1. Define a subclass of junit.framework.TestCase.
   2. Override the setUp() and tearDown() methods.
   3. Define multiple "public void testXXX()" methods. 
      One for each test. 
      A test method name must be started with "test".
          Call the methods of tested object.
          Check the expected results with an assertXXX() method.
   4. Define a "public static void main()" method to run tests.
      Call "junit.textui.TestRunner.run()" to run all tests.

Here is a nice example:

import junit.framework.*;
import junit.textui.*;
// by FYICenter.com
public class MathTestAndRun extends TestCase {
    protected double fValue1;
    protected double fValue2;

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

    protected void setUp() {
        fValue1= 2.0;
        fValue2= 3.0;
    }

    public void testAdd() {
        double result= fValue1 + fValue2;
        assertTrue(result == 5.0);
    }

    public void testMultiply() {
        double result= fValue1 * fValue2;
        assertTrue(result == 6.0);
    }
}

(Continued on next question...)

Other Interview Questions