Pass a Clock
implementation
The Answer by Jonathan is correct. The Clock
class offers several alternate implementations that tell a lie, to facilitate testing. Here is more explanation how to use them.
Every now
method in java.time take an optional Clock
argument.
The classes representing a moment:
The classes not representing a moment:
If omitted, you get the system default Clock
implementation, the true clock.
The Clock
class offers several handy alternate implementations, available by calling static class methods. See my Answer on a similar Question for a list with descriptions.
If you want to override that true clock with a false clock for testing purposes, pass some other Clock
implementation.
As an example, we make a Clock
that falsely reports a fixed single moment, a clock that does not “tick”. We set that single moment to be two hours from now.
Clock twoHoursFuture =
Clock.fixed(
Instant.now().plus( Duration.ofHours( 2 ) ) , // Capture the current moment, then add a `Duration` span-of-time of two hours. Result is a moment in the future.
ZoneId.systemDefault() // Or specify another time zone if that is an aim of your testing.
)
;
Given some code such as this method:
public void someMethod( Clock clock ) {
…
ZonedDateTime zdt = ZonedDateTime.now( clock ) ;
…
}
… your test harness passes a false clock:
// Test harness passes `twoHoursFuture`.
someObject.someMethod( twoHoursFuture ) ;
… while your production code passes the true clock, obtained by calling Clock.systemDefaultZone()
:
// Production-code passes the result of calling `Clock.systemDefaultZone()`.
someObject.someMethod( Clock.systemDefaultZone() ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.