Saturday, December 31, 2011

Single JUnit Test Class to Define Multiple Tests and Run Them

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.
Below is a nice example:
  1. package test;
  2. import junit.framework.TestCase;
  3. public class MathTestAndRun extends TestCase {
  4.    protected double fValue1;
  5.    protected double fValue2;
  6.    public static void main(String[] a){
  7.        junit.textui.TestRunner.run(MathTestAndRun.class);
  8.    }
  9.    
  10.    protected void setUp() {
  11.        fValue1= 2.0;
  12.        fValue2= 3.0;
  13.    }
  14.    public void testAdd() {
  15.        double result= fValue1 + fValue2;
  16.        assertTrue(result == 5.0);
  17.    }
  18.    public void testMultiply() {
  19.        double result= fValue1 * fValue2;
  20.        assertTrue(result == 6.0);
  21.    }
  22. }

No comments:

Post a Comment