Skip to content

Instantly share code, notes, and snippets.

@gaetancollaud
Created September 10, 2024 12:07
Show Gist options
  • Save gaetancollaud/4961fa5c08122fe064540b998c1f1288 to your computer and use it in GitHub Desktop.
Save gaetancollaud/4961fa5c08122fe064540b998c1f1288 to your computer and use it in GitHub Desktop.
dummy Java Clock mock to timetravel in unit tests
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
/** Clock used so we can shift time in tests. */
public class MockClock extends Clock {
private final Instant instant;
private Duration shift;
public MockClock() {
this(Instant.now().truncatedTo(ChronoUnit.HOURS));
}
public MockClock(Instant base) {
this.instant = base;
this.shift = Duration.ZERO;
}
public synchronized void shiftAbsolute(Duration shift) {
assert shift != null;
this.shift = shift;
}
public synchronized void shiftRelative(Duration shift) {
assert shift != null;
this.shift = this.shift.plus(shift);
}
@Override
public ZoneId getZone() {
return ZoneId.systemDefault();
}
@Override
public Clock withZone(ZoneId zone) {
return new MockClock(instant);
}
@Override
public Instant instant() {
return instant.plus(shift);
}
}
class MyTest {
private MockClock clock;
private MyObjectThatUseClock other;
@BeforeEach
void setUp() {
clock = new MockClock();
other = new MyObjectThatUseClock(clock);
}
@Test
void should_work() {
assertThat(other.getState()).isEqualTo(State.INITIALIZING);
clock.shiftAbsolute(Duration.ofSeconds(9));
other.recomputeState();
assertThat(other.getState()).isEqualTo(State.INITIALIZING);
clock.shiftAbsolute(Duration.ofSeconds(11));
other.recomputeState();
assertThat(other.getState()).isEqualTo(State.PROCESSING);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment