3. Making a Test Suite

Two additional steps are needed to run the two test cases:

  1. define how to run an individual test case,

  2. define how to run a test suite.

JUnit supports two ways of running single tests:

Static way: you override the runTest method inherited from TestCase and call the desired test case. A convenient way to do this is with an anonymous inner class. Note that each test must be given a name, so you can identify it if it fails.

TestCase test= new MoneyTest("simple add") {
    public void runTest() {
        testSimpleAdd();
    }
};

Dynamic way: it uses reflection to implement runTest. It assumes the name of the test is the name of the test case method to invoke. It dynamically finds and invokes the test method. To invoke the testSimpleAdd test we therefore construct a MoneyTest as shown below:

TestCase test= new MoneyTest("testSimpleAdd");

The dynamic way is more compact to write but it is less static type safe. An error in the name of the test case goes unnoticed until you run it and get a NoSuchMethodException.

As the last step to getting both test cases to run together, we have to define a test suite:

In JUnit this requires the definition of a static method called suite.

TestSuite and TestCase both implement an interface called Test which defines the methods to run a test. This enables the creation of test suites by composing arbitrary TestCases and TestSuites. The code below illustrates the creation of a test suite with the dynamic way to run a test.

public static Test suite() {
    TestSuite suite= new TestSuite();
    suite.addTest(new MoneyTest("testEquals"));
    suite.addTest(new MoneyTest("testSimpleAdd"));
    return suite;
}

or

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

Here is the corresponding code using the static way.

public static Test suite() {
    TestSuite suite= new TestSuite();
    suite.addTest(
        new MoneyTest("money equals") {
            protected void runTest() { testEquals(); }
        }
    );
    
    suite.addTest(
        new MoneyTest("simple add") {
            protected void runTest() { testSimpleAdd(); }
        }
    );
    return suite;
}