JUnit Frequently Asked Questions


  • How do I implement a test case for a thrown exception?
  • How do I organize my test cases?


  • How do I implement a test case for a thrown exception?

    Catch the exception and if it isn't thrown call the fail method. Fail signals the failure of a test case. Here is an example:
    public void testIndextOutOfBoundsException() {
        Vector v= new Vector(10)
        try {
             Object o= v.elementAt(v.size());
             fail("Should raise an ArrayIndexOutOfBoundsException");
        } catch (ArrayIndexOutOfBoundsException e) {
        }
    }

    How do I organize my Test Cases?

    Here is one way:
    1. create a test package for each of your application packages. For example, for a package myapp.util define myapp.utiltest. Put all the fixtures for the util package into this package.
    2. in myapp.utiltest define a class which creates a suite with all the tests in this package. To do so define a class AllTests which includes a single static suite method. Here is an example:

    3.  public static Test suite() {
        TestSuite suite= new TestSuite();
        suite.addTest(Fixture1.suite());
        suite.addTest(Fixture2.suite());
        return suite;
       }
    4. define similar AllTests classes that create higher level suites containing the suites from other test packages.
    When the fixtures are in a separate test package  the test cases don't have access to the methods and fields with default visibility ("package visible"). A variation of the above convention is to put all fixtures into the application package itself. This gives the fixtures access to all the package visible methods and fields. To separate the fixture classes from the production classes put them into a separate directory that you then add to the CLASSPATH. This makes it easy to ship the production classes independent of the fixtures. Here is an example for how to do this:
    1. put the fixtures classes for myapp.util into a TESTDIR\tests\myapp\util directory,
    2. add the tests directory to your CLASSPATH.