JUnit is an effective, and popular package for unit testing in Java.

Here's a cut-and-paste template for a test case in JUnit. Just set the mypackage to whichever package your class resides in, and then run search-replace Template with your class name. Then all you need to do is to start writing tests (testXXX stands for a ready template).

A couple of points:

  • Yes, the testXXX() template throws an Exception. This is to make your development faster - since JUnit catches all exceptions anyway, you don't have to worry about what exceptions might be thrown by your test case.
  • I usually construct a different hierarchy for tests (tests/com/ecyrd/jspwiki/) for example, so that I can keep the test code separate from the production code. However, the test classes are still declared to be in the same package as the classes they're testing, so that they have access to protected and package methods.
  • In addition, you want to have a very simple way of running your test cases - probably a good way is to write a shell script (or .BAT for Windows users). It's recommended that this script does a full clean of all class files before recompilation, so that you get to catch all those nasty API changes as well. Using Ant would probably be a good idea, as it has very good support for running JUnit test cases.

package mypackage;

import junit.framework.*;

public class Template extends TestCase
{
    public Template( String s ) { super(s); }

    public void setUp()
    {
    }
 
    public void tearDown()
    {
    }

    public void testXXX()
        throws Exception
    {
    }

    public static Test suite()
    {
        return new TestSuite( Template.class );
    }

    /**
     *  Starting this class directly runs the tests
     *  for this class only using the text interface
     */
    public static void main( String[] argv )
    {
        junit.textui.TestRunner.run(suite());   
    }
}

You also will probably need an AllTests routine for easy collecting of testcases:

package mypackage;

import junit.framework.*;

public class AllTests extends TestCase
{
    public AllTests( String name )
    {
        super(name);
    }               

    public static Test suite()
    {
        TestSuite suite = new TestSuite("Mypackage test suite.");           

        suite.addTest( mypackage.Template.suite() );

        return suite;
    }

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

Add new attachment

Only authorized users are allowed to upload new attachments.
« This page (revision-4) was last changed on 23-May-2006 22:48 by Janne Jalkanen