How to Test Time Randomness and IDs Deterministically
Make tests deterministic by injecting Clock, a Random seed and an id supplier, instead of calling now, Math.random and UUID.randomUUID inside the code.

A test that passes in the morning and fails at midnight, or only in a different time zone, depends on a hidden input. So does a test that uses a random value and fails one run in fifty. The remedy is mechanical: make each source of variation a parameter. This uses JDK 25 and JUnit Jupiter 6, with Spring Boot 4 for wiring. The wider cause list for flaky tests is in flaky tests.
Time
// hard to test
class TokenService {
boolean expired(Token t) { return t.expiresAt().isBefore(Instant.now()); }
}Replace the call with a Clock:
class TokenService {
private final Clock clock;
TokenService(Clock clock) { this.clock = clock; }
boolean expired(Token t) { return t.expiresAt().isBefore(clock.instant()); }
}@Test
void tokenExpiresAtTheDeadline() {
var now = Instant.parse("2026-03-14T09:30:00Z");
var service = new TokenService(Clock.fixed(now, ZoneOffset.UTC));
assertThat(service.expired(new Token(now.minusSeconds(1)))).isTrue();
assertThat(service.expired(new Token(now.plusSeconds(1)))).isFalse();
}Clock.fixed always returns the same instant. For code that waits, a mutable test clock moves time forward:
class MutableClock extends Clock {
private Instant now;
private final ZoneId zone;
MutableClock(Instant start, ZoneId zone) { this.now = start; this.zone = zone; }
void advance(Duration d) { now = now.plus(d); }
@Override public Instant instant() { return now; }
@Override public ZoneId getZone() { return zone; }
@Override public Clock withZone(ZoneId z) { return new MutableClock(now, z); }
}Now a session timeout of 30 minutes is tested by calling advance(Duration.ofMinutes(31)), with no sleep. In Spring, provide @Bean Clock clock() { return Clock.systemUTC(); } and override it in tests. The time zone issues in APIs are in dates and time zones.
Randomness
class Shuffler {
private final RandomGenerator random;
Shuffler(RandomGenerator random) { this.random = random; }
<T> List<T> shuffled(List<T> items) {
var copy = new ArrayList<>(items);
Collections.shuffle(copy, random instanceof Random r ? r : new Random(random.nextLong()));
return copy;
}
}In production pass new SecureRandom() or ThreadLocalRandom-backed generators; in tests pass new Random(42). The same seed gives the same sequence every run. For property-based or fuzz style tests that want random input, generate the seed, run, and print it so a failure can be reproduced:
long seed = System.nanoTime();
System.out.println("seed=" + seed);
var random = new Random(seed);Re-running with the printed seed repeats the failure. Do not use a seeded Random for security: tokens need SecureRandom, which you can wrap behind an interface if you need predictable values in tests.
Identifiers
interface IdGenerator { String next(); }
class OrderService {
private final IdGenerator ids;
OrderService(IdGenerator ids) { this.ids = ids; }
Order create() { return new Order(ids.next()); }
}
// test
var counter = new AtomicInteger();
IdGenerator sequential = () -> "order-" + counter.incrementAndGet();Expectations become exact: the first order is order-1. For UUID.randomUUID() in production, the lambda UUID::randomUUID suits the interface.
Other hidden inputs
| Input | Replace with |
|---|---|
System.getenv, System.getProperty | A configuration object |
| Default locale and charset | Explicit values in the code under test |
Iteration order of HashMap and HashSet | Sorted or ordered collections in assertions |
| File system state | @TempDir, see temporary directories |
| Thread scheduling | Injected executors, latches, or Awaitility |
Checking for leftovers
Run the suite with a different time zone and locale to flush out dependence:
./mvnw test -DargLine="-Duser.timezone=Pacific/Kiritimati -Duser.language=tr"The Turkish locale famously breaks code that upper-cases strings with the default locale. A failure here reveals an implicit input.
Why flaky tests cost more than they seem
A test that fails one run in fifty teaches a team to rerun the pipeline and ignore red builds. After a few months nobody trusts a failure, and a real bug passes through because the failing test was assumed to be flaky. The cost of a flaky test is not the minutes of the rerun, it is the lost meaning of a failure. That is why the sources of nondeterminism are worth removing at the root, with a seam in the code, and not worked around with retries and sleeps.
The shape of a seam
The pattern is the same for time, randomness and identifiers. The code under test receives the source as a constructor argument, with a production implementation that is the real thing, and the test passes a fixed one. For time that is java.time.Clock, with Clock.systemUTC() in production and Clock.fixed(...) in the test. For randomness it is a RandomGenerator or a supplier that the test seeds. For ids it is a Supplier<UUID> or a small interface. Keep the seam small and named for what it provides, so production code stays readable and a reader does not wonder why a class takes five suppliers.
class SessionService {
private final Clock clock;
SessionService(Clock clock) { this.clock = clock; }
boolean isExpired(Session s) {
return Instant.now(clock).isAfter(s.expiresAt());
}
}
@Test
void sessionExpiresAfterDeadline() {
Clock clock = Clock.fixed(Instant.parse("2026-01-01T12:00:00Z"), ZoneOffset.UTC);
var service = new SessionService(clock);
assertTrue(service.isExpired(new Session(Instant.parse("2026-01-01T11:59:59Z"))));
}Waiting for asynchronous work
A Thread.sleep(500) in a test is a guess about how long something takes, and it is wrong on a slow CI machine and wasteful on a fast one. Replace it with a condition. Awaitility polls until a condition holds or a timeout passes: await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(1, repository.count())). The test finishes as soon as the work does, and when it fails, the message states what was expected. For code that uses a scheduler, inject the executor and run a single-threaded one in the test, or run tasks directly, so the test controls when the work happens.
Ordering, shared state and the environment
The remaining sources are quieter. Tests that pass only in a certain order share state, through a static field, a singleton, a database row or a file in a temp directory. Run the suite in random order occasionally, with JUnit's junit.jupiter.testclass.order.default and junit.jupiter.testmethod.order.default set to random, to expose them. Default locale and time zone change formatting and date arithmetic, so set both in the build, with -Duser.timezone=UTC and -Duser.language=en in the Surefire arguments, or the tests that pass in your city fail on a CI server in another. Hash-based collections have no promised iteration order, so a test that compares a HashMap's key order is a time bomb. Sort before asserting, or use an assertion that ignores order.
Property-based thinking for randomness
A fixed seed makes a random test repeatable, but it also means you test one sequence. For code whose correctness does not depend on the particular values, such as a sorting routine or a parser, generate many random inputs and assert a property that must always hold, for example that sorting twice gives the same result as sorting once. Libraries such as jqwik do this, and print the seed and a shrunk failing example when a property fails, so the failure is reproducible. Use a fixed seed in the quick unit run and let a nightly job use fresh seeds, and record the seed in the output of every run so a failure at night can be replayed in the morning.
A quick audit
Search the main code for Instant.now(), LocalDate.now(), new Random(), Math.random(), UUID.randomUUID() and System.currentTimeMillis(). Each hit in code under test is a candidate seam. Do not fix them all at once. Start with the ones whose tests have failed at least once without a code change, since those already told you where the trouble is.
Where this does not apply
Do not inject a clock into trivial code that never branches on time. The cost is a constructor parameter; use it where behaviour depends on the moment. See the Clock Javadoc and RandomGenerator.


