Skip to content

Instantly share code, notes, and snippets.

@tkrueger
Created October 10, 2013 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkrueger/6915656 to your computer and use it in GitHub Desktop.
Save tkrueger/6915656 to your computer and use it in GitHub Desktop.
Design for testability: example of using wrappers around static method calls
public class ClockExample {
public class Clock {
public long now() {
return System.currentTimeMillis();
}
}
public class TestClock extends Clock {
DateTime current = DateTime.now();
@Override
public long now() {
return current.getMillis();
}
public void addMinutes(int minutes) {
current = current.plusMinutes(minutes);
}
public void setTimeTo(DateTime now) {
current = now;
}
}
public class Alarm {
Clock clock;
private final DateTime ringAt;
public Alarm(DateTime ringAt, Clock clock) {
this.ringAt = ringAt;
this.clock = clock;
}
public boolean isRinging() {
return ringAt.isBefore(clock.now());
}
}
@Test
public void alarmRingsWhenItsTime() throws Exception {
DateTime alarmTime = new DateTime(2013, 10, 10, 14, 23, 0);
TestClock clock = new TestClock();
clock.setTimeTo(alarmTime.minusMinutes(1));
Alarm alarm = new Alarm(alarmTime, clock);
assertThat(alarm.isRinging(), is(false));
clock.addMinutes(3);
assertThat(alarm.isRinging(), is(true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment