The previous section shows how to define new tests. This section describes how to organize test cases into test suites.
The recipe 'JUnit 1.2: How to compose a test suite' completes the set of recipes that guide the principal adaptation of JUnit. The TestSuite class applies the Composite construction principle, except that the generalization is fixed (see Figure 6.3). This means that no additional direct subclass of Test shall be defined in the application.[1] For that reason, a JUnit adaptation only defines subclasses of TestCase.
[1] Since Test is an interface, this means that no additional direct implementations of the interface should be defined. In this case, the only valid implementations for Test are TestCase and TestSuite.
A method suite() is used to define new test suites. For convenience, it can be defined as a static method in a TestCase subclass. Figure 6.12 shows a sequence diagram which illustrates how a test suite is created. The method suite() creates a TestSuite object and adds the set of test cases by invoking addTest() for each test case or test suite object that should be part of the test suite.
Table 6.6 describes the steps for defining a JUnit test suite. If inner classes have been used to define test cases, then the instances of inner subclasses of a test case have to be composed in a test suite. Thus, the previous recipe 'JUnit 1.1A' and the presented 'JUnit 1.2' are to some extent intertwined.
When JUnit is launched, for example through a Java command line interface, it takes the name of a TestCase subclass as parameter, invokes its suite() method getting a test suite object as result, and invokes the run() method on that test suite.
Recipe 'JUnit 1.2: How to compose a test suite' | |
---|---|
Intent | A number of tests have been defined and shall be composed to a single test suite. A new test suite shall combine a number of already existing tests and test suites. |
Classes | TestSuite and TestCase. |
Steps to Apply |
|
Discussion | In addition to creating class-wide test suites, it is often useful to compose package, subsystem and finally system-wide test suites. Their possibly overlapping contents of tests make them less manageable over time. However, it might be worthwhile to define short life test suites that focus on particular features of the system if the overall runtime of a complete test suite is considerable. |
Based on the recipe 'JUnit 1.2: How to compose a test suite', we derive a compact suite() implementation as shown in Example 6.7.
public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new ComplexTest ("testAddZeroZero") { protected void runTest() { this.testAddZeroZero(); } }); suite.addTest(new ComplexTest("testAddCommuting"){ protected void runTest() { this.testAddCommuting(); } } ); suite.addTest(new ComplexTest("testEquals"){ protected void runTest() { this.test Equals();} }); return suite; }