Section 34.2. Changing the Date


34.2. Changing the Date

"Let's review the way that the date is changed in the tests," suggested Emily. Figure 34.1 shows a table with the action time is now for changing the current date and time, as used in Chapter 15.

Figure 34.1. Set the Date/Time

time is now

2004/05/06 09:01


"So that means that we need a method timeIsNow() in the fixture, and we need a mock clock for testing," Neo suggested.

"Yes, and we'll need a way to change the current date/time in the mock," added Emily, "and we need to pass the mock clock to the application."

Listing 34.4 shows part of the fixture class StartApplication, which Emily altered to deal with the date. When an object of class StartApplication is created, it creates a MockClock object, which is passed in the constructor to the system under test, the RentEz object.

Listing 34.4. StartApplication.java (part 1)
 public class StartApplication extends DoFixture {    private final MockClock mockClock = new MockClock();    private RentEz rentEz;    public StartApplication() throws Exception {       rentEz = new RentEz(mockClock);    }    public boolean timeIsNow(Date time) {       mockClock.setTime(time);       return true;    }    // ... } 

It works well to create the MockClock in the fixture and pass it into the application, because then the date/time can easily be changed by the fixture object. For the action time is now in Figure 34.1, the corresponding method timeIsNow() in Listing 34.4 calls the setTime() method of the MockClock.

The timeIsNow() method returns true, so the corresponding Fit action will be reported in green. This is what Don wanted, so he could see that the time had been changed.

Emily's class MockClock is shown in Listing 34.5. It simply maintains the last date/time that it was set to and supplies that Date in method getTime().

The application needs to run in either test mode or in normal operation. To run in test mode, a RentEz object is created with a MockClock as an argument, as shown with the added constructor in class RentEz in Listing 34.6.

Listing 34.5. MockClock.java
 public class MockClock implements Clock {    private Date currentTime;    public void setTime(Date time) {       currentTime = time;    }    public Date getTime() {       return currentTime;    } } 

Listing 34.6. RentEz.java (version 2)
 public class RentEz {    private Clock clock;    public RentEz(Clock clock) {        this.clock = clock;    }    public RentEz() {        clock = new SystemClock();    }    public Date getTime() {       return clock.getTime();    }    // ... } 



    Fit for Developing Software. Framework for Integrated Tests
    Fit for Developing Software: Framework for Integrated Tests
    ISBN: 0321269349
    EAN: 2147483647
    Year: 2005
    Pages: 331

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net