The trick is to create a time provider mockup.
In Ruby, you simply use the mock library:
now = Time.now Time.expects (: now) .returns (now) .once Time.expects (: now). Returns (now + 1) .once, etc.
In Java, this is a little trickier. Replace the usual time with your "Clock"
interface Clock { Date getNow(); }
and then rewrite:
public String elapsedTime(Date d) { final Date now = new Date(); final long ms = now.getTime() - d.getTime(); return "" + ms / 1000 + " seconds ago"; }
as:
public String elapsedTime(Date d, Clock clock) { final Date now = clock.getNow(); final long ms = now.getTime() - d.getTime(); return "" + ms / 1000 + " seconds ago"; }
Obviously, Clock can be entered in other ways, but now we have a testable and extensible method.
source share