2

Have you ever encounter such a scenario:

Need to test some date related functionality of your software, the software rely on OS to get current date, so we have to change the date of OS, but date & time is actually a critical service in any OS, changing date & time of OS may cause problems, for example some application server check last-modified date to decide whether to recompile JSP files.

Is there any smart way to handle such problems, like set date & time on JVM level or application level ?

WestFarmer
  • 669
  • 8
  • 27

1 Answers1

5

If you use Java 8 and the classes of java.time, you can use Clock. At normal application run time you can then inject and use the normal system clock provided by Clock.systemDefaultZone(), for tests you can inject a Clock instance with a fixed time, for example provided by Clock.fixed or subclassing Clock if you need more control.

You would then need to change your code to something like:

// Inject this value somehow, eg using Spring
private Clock clock;

public LocalDateTime methodThatGeneratesTime() {
    return LocalDateTime.now(clock); // Instead of just LocalDateTime.now()
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • We can't use java 8 right now, but I will try ThreeTen Backport with JDK 6. – WestFarmer Dec 31 '16 at 11:26
  • 1
    The [`java.time.Clock`](http://docs.oracle.com/javase/8/docs/api/java/time/Clock.html) class offers other altered-clock implementations in addition to `fixed`. See [my Answer](http://stackoverflow.com/a/26570951/642706) to a duplicate Question for a list with descriptions. So, not likely any need to roll-your-own override of `Clock`. – Basil Bourque Dec 31 '16 at 19:01
  • @BasilBourque Good to know, I haven't had the chance to use it much yet, and I have seen a colleague using a subclass in one of our tests, so I assumed that for some use cases it might be necessary. – Mark Rotteveel Dec 31 '16 at 20:41