|
13.6. Running Test SuitesQuite likely, you'll want to run several tests, exercising the various classes that make up your application. Let's see an example of how to build such a suite of tests (Example 13.3). While not defined as an interface, the convention is used by JUnit TestRunner classes that they will look for a public static method called suite() in any class that you ask a TestRunner to run. Your class, the one that will define the suite of tests, should return something that implements the Test interface. A TestSuite object is one such object, and we can fill it with tests gleaned automatically by JUnit from the class names that we supply. We've also added a main() that invokes the text-based user interface for running these tests. That way you can invoke the tests from the command line if you like. Here are the two commands to compile and execute the CoreTest suite, using the Swing GUI: $ javac test/net/multitool/core/CoreTest.java $ java junit.swingui.TestRunner net.multitool.core.CoreTest When the GUI runs, click on the Hierarchy tab and you can see the various tests that make up the suite. Opening the folders will show the tests inside of suites (Figure 13.4). Figure 13.4. The CoreTest running a suite of tests
Example 13.3. A suite of test casespackage net.multitool.core; import junit.framework.*; public class CoreTest extends TestCase { public CoreTest(String str) { super(str); } // constructor CoreTest /** * Constructs a collection of tests to be run by the TestRunner. */ public static Test suite() { /* * Add the results of each separate Test into a big Suite. */ TestSuite suite = new TestSuite("Core Classes"); suite.addTestSuite(net.multitool.util.SAMoneyTest.class); suite.addTestSuite(AccountTest.class); suite.addTestSuite(UserTest.class); return suite; } // suite public static void main(String [] args) { junit.textui.TestRunner.run(suite()); } // main } // class CoreTest One last example is the SAMoneyTest.java file that was used in the CoreTest example (Figure 13.4). Did you notice the names displayed in the test hierarchy? They don't match the method names used to run the tests in SAMoneyTest.java because we constructed the suite "by hand" instead of letting the JUnit introspection and reflection find the methods dynamically. Such manual approach has some advantages. You can restrict the current set of tests being executed to a subset of the entire set of tests. You can also, as this example shows, give other names to the tests. The biggest drawback, though, is the maintenance cost of having to add the test by hand to the suite() method whenever you add another test method. |
|