- CourseSession
- Enrolling Students
- int
- Initialization
- Default Constructors
- Suites
- The SDK and java.util.ArrayList
- Adding Objects
- Incremental Refactoring
- Objects in Memory
- Packages and the import Statement
- The java.lang Package
- The Default Package and the package Statement
- The setUp Method
- More Refactoring
- Class Constants
- Dates
- Overloaded Constructors
- Deprecation Warnings
- Refactoring
- Creating Dates with Calendar
- Comments
- Javadoc Comments
- Exercises
Suites
In the last section, you introduced a second test class, CourseSessionTest. Going forward, you could decide to run JUnit against either CourseSessionTest or StudentTest, depending on which corresponding production class you changed. Unfortunately, it is very possible for you to make a change in the Student class that breaks a test in CourseSessionTest, yet all the tests in StudentTest run successfully.
You could run the tests in CourseSessionTest and then run the tests in StudentTest, either by restarting JUnit each time or by retyping the test class name in JUnit or even by keeping multiple JUnit windows open. None of these solutions is scalable: As you add more classes, things will quickly become unmanageable.
Instead, JUnit allows you to build suites, or collections of tests. Suites can also contain other suites. You can run a suite in the JUnit test runner just like any test class.
Create a new class called AllTests with the following code:
public class AllTests { public static junit.framework.TestSuite suite() { junit.framework.TestSuite suite = new junit.framework.TestSuite(); suite.addTestSuite(StudentTest.class); suite.addTestSuite(CourseSessionTest.class); return suite; } }
If you start JUnit with the class name AllTests, it will run all of the tests in both CourseSessionTest and StudentTest combined. From now on, run AllTests instead of any of the individual class tests.
The job of the suite method in AllTests is to build the suite of classes to be tested and return it. An object of the type junit.framework.TestSuite manages this suite. You add tests to the suite by sending it the message addTestSuite. The parameter you send with the message is a class literal. A class literal is comprised of the name of the class followed by .class. It uniquely identifies the class, and lets the class definition itself be treated much like any other object.
Each time you add a new test class, you will need to remember to add it to the suite built by AllTests. This is an error-prone technique, as it's easy to forget to update the suite. In Lesson 12, you'll build a better solution: a tool that generates and executes the suite for you.
The code in AllTests also introduces the concept of static methods, something you will learn about in Lesson 4. For now, understand that you must declare the suite method as static in order for JUnit to recognize it.