Agile Javaв„ў: Crafting Code with Test-Driven Development

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 duplicationa 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); ... } }

Caution!

It's easy to make the mistake of coding setUp so that it declares session as a local variable:

public void setUp() { CourseSession session = new CourseSession("ENGL", "101"); }

It is legal to define a local variable with the same name as an instance variable, but it means that the instance variable session will not get properly initialized. The result is an error known as a NullPointerException, which you'll learn about in Lesson 4.

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.

Категории