Skip to content

Instantly share code, notes, and snippets.

@darekmydlarz
Last active March 30, 2016 10:54
Show Gist options
  • Select an option

  • Save darekmydlarz/f08d2de398c80cb3b26a0cbaeefa93c2 to your computer and use it in GitHub Desktop.

Select an option

Save darekmydlarz/f08d2de398c80cb3b26a0cbaeefa93c2 to your computer and use it in GitHub Desktop.
How to test time dependent code in Java? [czystykod.pl]
public class Task {
public String getAction() {...}
public LocalDateTime getDueDate() {...}
public boolean isOverdue(Clock clock) {
return LocalDateTime.now(clock).isAfter(getDueDate());
}
}
class TaskSpec {
Clock fixedClock = Clock.fixed(Instant.now()), ZoneId.systemDefault());
def "task should become overdue when its' due date has come"() {
given:
LocalDateTime nowPlus10Seconds = LocalDateTime.now(fixedClock).plusSeconds(10);
Task task = Tasks.withDueDate(nowPlus10Seconds, "Call to Venkat")
expect:
task.isOverdue(fixedClock) == false
task.isOverdue(Clock.offset(fixedClock, Duration.ofSeconds(10))) == true
}
}
// DON'T DO THIS
public class WrongTask {
public String getAction() {...}
public Date getDueDate() {...}
public boolean isOverdue() {
return System.currentTimeMillis() > getDueDate().getMillis();
}
}
// DON'T DO THIS
class WrongTaskSpec {
def "task should become overdue when its' due date has come"() {
given:
Date nowPlus10Seconds = new Date(System.currentTimeMillis() + TEN_SECONDS_AS_MS)
Task task = Tasks.withDueDate(nowPlus10Seconds, "Call to Venkat")
expect:
task.isOverdue() == false
TimeUnit.SECONDS.sleep(10)
task.isOverdue() == true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment