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:
By explicit calls to TestCase
By test class (J2SE only)
By creating the suite() method
A TestSuite can only contain objects derived from TestCase or a TestSuite that contains a 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.
TestSuite suiteAllTests = new TestSuite() ;
suiteAllTests.AddTest(SuiteStocks);
suiteAllTests.AddTest(OthersTests.class);
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());
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