| Modifier and Type | Method and Description |
|---|---|
void |
clearObservers()
Remove all registered observers.
|
Clock |
clock()
Returns the clock.
|
void |
fastBackward(Duration duration)
Jump the clock backward by the given duration.
|
void |
fastForward(Duration duration)
Jump the clock forward by the given duration.
|
Instant |
now()
Returns the current instant using the clock.
|
void |
registerObserver(Consumer<Clock> clockConsumer)
Register an observer that will be notified every time the clock is changed by
fastForward(Duration), fastBackward(Duration) or timeFlow(Duration, Instant, int). |
void |
resetClock()
|
void |
setClock(Clock clock)
|
static TestTime |
testInstance()
Returns the singleton instance of TestTime.
|
void |
timeFlow(Duration step,
Instant endTime,
int flowSpeedMillis)
Simulate time flow by jumping the clock forward by the given step every flowSpeedMillis.
|
public static TestTime testInstance()
public Instant now()
public Clock clock()
Clock.systemUTC().public void setClock(Clock clock)
Time and TestTime with a custom one.
// Prepare a fixed clock
ZoneId zoneId = TimeZone.getTimeZone("Europe/Warsaw").toZoneId();
ZonedDateTime dateTime = LocalDateTime.of(2001, 11, 23, 12, 15).atZone(zoneId);
Clock fixedClock = Clock.fixed(dateTime.toInstant(), zoneId);
// Set the fixed clock as the clock used by Time in the production code
TestTime.testInstance().setClock(fixedClock);
public void resetClock()
public void fastForward(Duration duration)
duration - the duration to jump forwardpublic void fastBackward(Duration duration)
duration - the duration to jump backwardpublic void timeFlow(Duration step, Instant endTime, int flowSpeedMillis)
Time in the production code.
// Prepare a fixed clock
ZoneId zoneId = TimeZone.getTimeZone("Europe/Warsaw").toZoneId();
ZonedDateTime dateTime = LocalDateTime.of(2001, 11, 23, 12, 15).atZone(zoneId);
Clock fixedClock = Clock.fixed(dateTime.toInstant(), zoneId);
// Set the fixed clock as the clock used by Time in the production code
TestTime.testInstance().setClock(fixedClock);
// Prepare time flow parameters
Duration step = Duration.of(1, ChronoUnit.MINUTES);
Instant endTime = fixedClock.instant().plus(10, ChronoUnit.MINUTES);
int flowSpeedMillis = 100;
// Simulate time flow
TestTime.testInstance().timeFlow(step, endTime, flowSpeedMillis);
step - the duration to jump forwardendTime - the time when the simulated time flow should stopflowSpeedMillis - the speed of the simulated time flow in millisecondsIllegalArgumentException - if flowSpeedMillis is not positive or endTime is before the
current timeRuntimeException - if interrupted while sleeping between jumpspublic void registerObserver(Consumer<Clock> clockConsumer)
fastForward(Duration), fastBackward(Duration) or timeFlow(Duration, Instant, int).
TestTime
.testInstance()
.registerObserver(clock -> System.out.println(clock.instant()));
clockConsumer - the observerpublic void clearObservers()
Copyright © 2023. All rights reserved.