Last active
March 30, 2016 10:54
-
-
Save darekmydlarz/f08d2de398c80cb3b26a0cbaeefa93c2 to your computer and use it in GitHub Desktop.
How to test time dependent code in Java? [czystykod.pl]
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 Task { | |
| public String getAction() {...} | |
| public LocalDateTime getDueDate() {...} | |
| public boolean isOverdue(Clock clock) { | |
| return LocalDateTime.now(clock).isAfter(getDueDate()); | |
| } | |
| } |
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
| 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 | |
| } | |
| } |
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
| // DON'T DO THIS | |
| public class WrongTask { | |
| public String getAction() {...} | |
| public Date getDueDate() {...} | |
| public boolean isOverdue() { | |
| return System.currentTimeMillis() > getDueDate().getMillis(); | |
| } | |
| } |
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
| // 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