Using the TestSuite class

Component Testing for Java

After writing several simple test cases, you will need to group the individual test classes derived from TestCase and run them together. This can be done with the TestSuite class.

There are three ways of constructing a TestSuite:

A TestSuite can only contain objects derived from TestCase or a TestSuite that contains a TestCase.

Construction by Explicit calls to TestCase

You can add the explicit calls to the TestSuite instance by instance, as in the following example:

TestSuite suiteStocks = new TestSuite() ;

suiteStocks.addTest(new TestStocks("testStocksValues"));

suiteStocks.addTest(new TestStocks("testStocksAmount"));

 

You can also directly pass the test object. In this case, the TestSuite automatically builds all the test classes from the public method names:

TestSuite suiteStocks = new TestSuite() ;

suiteStocks.addTest(TestStocks.class);

 

Such a TestSuite can be contained in another TestSuite.

Construction by Test Class

TestSuite suiteAllTests = new TestSuite() ;

suiteAllTests.AddTest(SuiteStocks);

suiteAllTests.AddTest(OthersTests.class);

 

Creating a suite() Method

In J2ME, to be able to build a TestSuite from a test class, you cannot pass the class object as sole argument. To resolve this, an extra suite() method is added to the test class, which returns a valid TestSuite:

TestSuite suiteStocks = new TestSuite() ;

suiteStocks.addTest(new TestStocks().suite());

Running a TestSuite

In J2SE, you run a test suite exactly as you would run a test class, either by producing a TestResult object, or by modifying the TestResult passed as a parameter, as in the following examples:

TestResult result = suiteAllTests.run(result);

 

TestResult result = new TestResult() ;

suiteAllTests.run(result);

 

In J2ME, in order to save memory, the TestSuite destroys the last TestCase instance after each run.

Related Topics

Using the TestCase ClassUsing the TestResult Class