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 ?

3

1 Answer 1

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() } 
Sign up to request clarification or add additional context in comments.

3 Comments

We can't use java 8 right now, but I will try ThreeTen Backport with JDK 6.
The java.time.Clock class offers other altered-clock implementations in addition to fixed. See my Answer to a duplicate Question for a list with descriptions. So, not likely any need to roll-your-own override of Clock.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.