- 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
The setUp Method
The test code in CourseSessionTest needs a bit of cleanup work. Note that both tests, testCreate and testEnrollStudents, instantiate a new CourseSession object and store a reference to it in a local variable named session.
JUnit provides you with a means to eliminate this duplication—a setUp method. If you provide code in this setUp method, JUnit will execute that code prior to executing each and every test method. You should put common test initialization code in this method.
public class CourseSessionTest extends TestCase { private CourseSession session; public void setUp() { session = new CourseSession("ENGL", "101"); } public void testCreate() { assertEquals("ENGL", session.getDepartment()); assertEquals("101", session.getNumber()); assertEquals(0, session.getNumberOfStudents()); } public void testEnrollStudents() { Student student1 = new Student("Cain DiVoe"); session.enroll(student1); ... } }
In CourseSessionTest, you add the instance variable session and assign to it a new CourseSession instance created in the setUp method. The test methods testCreate and testEnrollStudents no longer need this initialization line. Both test methods get their own separate CourseSession instance.
Even though you could create a constructor and supply common initialization code in it, doing so is considered bad practice. The preferred idiom for test initialization in JUnit is to use the setUp method.