Sub topic 17
Making Time-Dependent Code Testable with Clock
Some code depends on the current time. A free trial expires after 30 days. A store shows a "Happy Monday" banner. A report covers "this month." Code like this gives a different answer each day, which makes it hard to test.
This chapter shows how the Clock class solves that problem. You will learn what a clock is, how to pass one into your code, and how to freeze time in a test.
Why `now()` Makes Testing Hard
A test is a small program that checks whether your code gives the right answer. A good test gives the same result every time you run it.
Look at this method:
import java.time.LocalDate;
public class Trial {
private final LocalDate endDate;
public Trial(LocalDate endDate) {
this.endDate = endDate;
}
public boolean isExpired() {
return LocalDate.now().isAfter(endDate);
}
}LocalDate.now() reads today's date from your computer. Suppose the trial ends on 2024-01-31. If you run a test on January 15, isExpired() returns false. If you run the same test in March, it returns true. The code did not change, but the test result did.
Your test also cannot check the expired case today unless you wait for the end date to pass. That is no way to test.
What a Clock Is
A Clock is an object in java.time that answers one question: "What time is it right now?" It holds two things:
- An instant, which is a point on the timeline (covered in the Instant chapter).
- A zone, which is the time zone used to turn that instant into a local date and time.
Every now() method in java.time has a version that takes a clock. These include LocalDate.now(clock), LocalTime.now(clock), LocalDateTime.now(clock), ZonedDateTime.now(clock), and Instant.now(clock). When you call now() with no arguments, Java uses the system clock for you.
So the fix is simple. Your code asks a clock for the time instead of asking the computer directly. Then you decide which clock to give it.
Freezing Time with `Clock.fixed`
A fixed clock is a clock that always reports the same instant. It never moves forward. That makes it a good fit for tests.
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
public class FixedClock {
public static void main(String[] args) {
Clock fixed = Clock.fixed(Instant.parse("2024-01-01T00:00:00Z"), ZoneOffset.UTC);
LocalDate today = LocalDate.now(fixed);
System.out.println(today); // 2024-01-01
}
}Clock.fixed takes an Instant and a zone. Here the zone is UTC. This program prints 2024-01-01 whether you run it today, tomorrow, or in ten years.
Passing a Clock Into Your Code
The common pattern is called dependency injection. It means a class receives the things it needs from outside, instead of creating them itself. Here, the class receives its clock through its constructor.
Here is the trial class rewritten to accept a clock:
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
public class TrialDemo {
static class Trial {
private final Clock clock;
private final LocalDate endDate;
Trial(Clock clock, LocalDate endDate) {
this.clock = clock;
this.endDate = endDate;
}
boolean isExpired() {
return LocalDate.now(clock).isAfter(endDate);
}
}
public static void main(String[] args) {
LocalDate end = LocalDate.of(2024, 1, 31);
Clock midTrial = Clock.fixed(Instant.parse("2024-01-15T10:00:00Z"), ZoneOffset.UTC);
Clock lastDay = Clock.fixed(Instant.parse("2024-01-31T10:00:00Z"), ZoneOffset.UTC);
Clock dayAfter = Clock.fixed(Instant.parse("2024-02-01T10:00:00Z"), ZoneOffset.UTC);
System.out.println(new Trial(midTrial, end).isExpired()); // false
System.out.println(new Trial(lastDay, end).isExpired()); // false
System.out.println(new Trial(dayAfter, end).isExpired()); // true
// In the real program, pass the system clock instead.
Trial real = new Trial(Clock.systemDefaultZone(), end);
System.out.println(real.isExpired()); // depends on today's date
}
}The Trial class itself does not know or care which clock it got. In the real application you pass Clock.systemDefaultZone(), which follows the real time. In a test you pass a fixed clock. You can now check the middle of the trial, the last day, and the day after, all in one second.
The last day is an edge case. An edge case is a value right at a boundary, where bugs often hide. With a fixed clock, testing edge cases is easy.
The Zone Inside a Clock Matters
A fixed clock stores an instant and a zone. The same instant can be a different calendar date in a different zone.
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class ClockZone {
public static void main(String[] args) {
Instant midnightUtc = Instant.parse("2024-01-01T00:00:00Z");
Clock utc = Clock.fixed(midnightUtc, ZoneId.of("UTC"));
Clock newYork = Clock.fixed(midnightUtc, ZoneId.of("America/New_York"));
System.out.println(LocalDate.now(utc)); // 2024-01-01
System.out.println(LocalDate.now(newYork)); // 2023-12-31
}
}Midnight in UTC is 7 p.m. the evening before in New York. So LocalDate.now(newYork) gives December 31. When you write a test, choose the zone your users actually live in. Otherwise a test that passes in one zone can fail in another.
Moving Time Forward with `Clock.offset`
Sometimes a test needs time to "pass." Clock.offset makes a new clock that is always a fixed amount ahead of (or behind) another clock.
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
public class OffsetClock {
public static void main(String[] args) {
Clock start = Clock.fixed(Instant.parse("2024-01-01T00:00:00Z"), ZoneOffset.UTC);
Clock later = Clock.offset(start, Duration.ofDays(45));
System.out.println(LocalDate.now(start)); // 2024-01-01
System.out.println(LocalDate.now(later)); // 2024-02-15
}
}The later clock is 45 days ahead of start. Like every java.time object, a clock is immutable. Clock.offset returns a new clock and leaves start unchanged.
Common Clock Factory Methods
A factory method is a static method that creates an object for you. These are the ones you will use most:
| Method | What it gives you | Typical use |
|---|---|---|
| `Clock.systemUTC()` | Real time, UTC zone | Servers, logging |
| `Clock.systemDefaultZone()` | Real time, computer's default zone | Simple desktop programs |
| `Clock.system(zone)` | Real time, the zone you choose | Apps tied to one region |
| `Clock.fixed(instant, zone)` | The same instant every time | Tests |
| `Clock.offset(clock, duration)` | Another clock shifted by a duration | Tests that need time to pass |
| `Clock.tickMinutes(zone)` | Real time rounded down to the minute | Ignoring seconds |
You can also read a clock directly. clock.instant() returns the current Instant, clock.millis() returns milliseconds since the epoch, and clock.getZone() returns its zone.
Summary
- Calling
now()with no arguments ties your code to the real computer time, which makes tests unreliable. - A
Clockprovides the current instant and a zone, and everynow()method accepts one. - Pass a clock into your class through its constructor. Use a system clock in production and
Clock.fixedin tests. - The clock's zone decides the local date, so pick it on purpose.
Clock.offsetcreates a clock shifted forward or backward for tests where time must pass.
Exercise
A method uses LocalTime.now() to decide whether a shop is open between 09:00 and 17:00. Rewrite the idea so you can test it at 08:59 and 09:00 on any day. Which clock would you pass in to test 09:00 in UTC on 2024-05-06?
Show answer
Give the class a Clock field set through the constructor and call LocalTime.now(clock) instead of LocalTime.now(). For the test, pass Clock.fixed(Instant.parse("2024-05-06T09:00:00Z"), ZoneOffset.UTC). For 08:59, use Instant.parse("2024-05-06T08:59:00Z").
Exercise
You create Clock.fixed(Instant.parse("2024-03-01T02:00:00Z"), ZoneId.of("America/Los_Angeles")). What does LocalDate.now(clock) print, and why?
Show answer
It prints 2024-02-29. Los Angeles is 8 hours behind UTC in March before daylight saving starts, so 02:00 UTC on March 1 is 18:00 on February 29 in Los Angeles. 2024 is a leap year.
Exercise
Starting from a fixed clock at 2024-01-01T00:00:00Z in UTC, how do you build a clock that reports 2024-01-08, and what is the original clock's date afterward?
Show answer
Use Clock.offset(start, Duration.ofDays(7)). The original clock still reports 2024-01-01, because clocks are immutable and offset returns a new clock.