SE450: JUnit: Creating a Suite of Tests [34/41] ![]() ![]() ![]() |
Tests should be run together, and it should be easy to do
this. The way that JUnit does this is by providing the
TestSuite
class. The TestSuite
is
a Composite pattern. It allows tests to be grouped and run
together.
There are two ways to create a TestSuite
, you
can create it dynamically or statically. When you do it
dynamically, you can create the test using the single
argument constructor, or you can allow JUnit to
generate your suite automatically (using Java Reflection).
Or to do it the type-safe way (so errors are caught at compile time)...
public static Test suite() { TestSuite suite= new TestSuite(); suite.addTest( new VectorTest("clone") { protected void runTest() { testClone(); } } ); return suite; }
How do you think the test gets run? Hint, it is via a pattern we have already studied.
To do it dynamically ...
public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new VectorTest("testClone")); suite.addTest(new VectorTest("testCapacity")); return suite; }
To do it automatically ...
public static Test suite() { return new TestSuite(VectorTest.class); }
In the automatic way, JUnit uses Java Reflection to take each method that starts with "test" and takes no arguments, and add it to the suite. If you use this method, make sure you follow the naming convention for tests. You should follow the convention either way, but ignoring it prevents you from using this time saver.
Note: you will most often want to use one of the latter two methods. They are more readable and easier to work with, and most examples will use that method.