Created
October 10, 2013 09:35
-
-
Save tkrueger/6915656 to your computer and use it in GitHub Desktop.
Design for testability: example of using wrappers around static method calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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