Lesson · Date & Time API
Testability: Clock, the seam for time
11 min readTestability
Code that calls Instant.now() directly is untestable: the answer changes every run. Clock turns 'what time is it' into a parameter, so tests can freeze the calendar, jump an hour, or prove an expiry boundary without a single sleep().
Time is the classic hidden dependency
A method that reads the system clock has an input you cannot control: the moment it runs. Tests compensate with sleeps (slow, flaky) or with tolerances (vague), and DST or leap-day bugs slip through both. The code is not wrong, it is simply holding a dependency it never declared.
The fix is the same as for any dependency: take it in. java.time models the clock itself as a type, and every now() method has an overload that accepts one.
Instant now = Instant.now(); // the hidden dependency Instant now = Instant.now(clock); // the seam: time arrives as a parameter
The four clocks
Clock is abstract with a small factory family. systemUTC and systemDefaultZone read the real machine; fixed pins one instant forever; offset shifts the real clock by a duration. Every java.time type accepts one: Instant.now(clock), LocalDate.now(clock), ZonedDateTime.now(clock).
| Clock | Reads | Use in |
|---|---|---|
| Clock.systemUTC() | the real timeline | production, storage, comparisons |
| Clock.systemDefaultZone() | the real timeline in machine zone | local displays when machine zone is meaningful |
| Clock.fixed(instant, zone) | always the same instant | tests: exact boundaries |
| Clock.offset(base, duration) | base plus a shift | tests: 'an hour later' without waiting |
Clock surgery · test the expiry boundary, not the sleep
wall time spent: 0 msservice under test
new Expiry(now.plusSeconds(30)) · isValid(token, clock) = clock.instant().isBefore(expiresAt)
the instant equals expiresAt. isBefore is strict, so the window closes exactly here: off-by-one bugs live on this line.
Fixed clocks test boundaries, not durations
An expiry that lives 30 seconds can be tested at three instants with a fixed clock: one second before expiry (valid), exactly at it, one second after (expired). Three assertions, zero seconds of wall time, and the boundary itself is exercised, which is where off-by-one expiry bugs live.
The same pattern covers token lifetimes, trial periods, cache TTLs and scheduled jobs: compute against the injected clock, and every test chooses its moment.
Expiry token = new Expiry(now.plusSeconds(30)); isValid(token, Clock.fixed(now.minusSeconds(1), ZoneOffset.UTC)); // true isValid(token, Clock.fixed(now.plusSeconds(31), ZoneOffset.UTC)); // false
Offset clocks move time without sleeping
When behavior depends on elapsed time rather than a boundary, an offset clock anchored to a fixed base acts like a controllable stopwatch: build the service once, then present it at 'T plus one hour' in the next test. No thread parking, no flakiness in CI.
For a clock that a test advances over time, a small mutable Clock subclass or a test library (the java.time community provides several) is the usual next step; the principle stays the same: the seam is the same everywhere.
Clock base = Clock.fixed(now, ZoneOffset.UTC); service.run(Clock.offset(base, Duration.ofHours(1))); // behaves as if an hour passed
Wire the system clock at the edge
The pattern that keeps production honest: services take a Clock in their constructor, defaulting to Clock.systemUTC(); one composition root (the main class, a framework, a test fixture) decides which clock the system runs on. Instant.now() with no argument survives only in that root and in throwaway code.
class Trial { private final Clock clock; Trial() { this(Clock.systemUTC()); } // production default Trial(Clock clock) { this.clock = clock; } // tests inject boolean isActive() { return Instant.now(clock).isBefore(endsAt); } }
If a class needs the time, its constructor should say so. A no-argument now() buried in business logic is a test that writes itself as 'run it and hope'.
Time is an input
Treat the clock like a database connection: inject it, default it at the edge, and never let business logic fetch it from the environment. Testing at exact boundaries then costs microseconds instead of sleep calls.
Interview angles
Why is calling Instant.now() inside domain logic a problem?+
It is an undeclared dependency on the environment. Tests cannot control it, so they either sleep (slow, flaky) or widen tolerances (vague). Injecting a Clock makes the moment an explicit input.
What does Clock.fixed provide?+
A clock that always returns the same instant, with a fixed zone. Tests use it to land exactly one second before, at, and after an expiry boundary, exercising the edge without any wall-clock waiting.
How do you test behaviour an hour after an event without sleeping?+
Use Clock.offset(fixedBase, Duration.ofHours(1)) (or advance a mutable test clock). The service computes against the shifted instant and behaves as if the hour passed.
Where should the system clock enter an application?+
At the composition root: constructors take a Clock (defaulting to Clock.systemUTC()) and pass it down. Business code calls now(clock), so production reads the real timeline while tests control it.
Does injecting Clock complicate production code?+
It is one constructor parameter with a default overload. The cost is a line per service; the payoff is every time-dependent path becoming deterministically testable, DST and boundaries included.