Created
September 10, 2024 12:07
-
-
Save gaetancollaud/4961fa5c08122fe064540b998c1f1288 to your computer and use it in GitHub Desktop.
dummy Java Clock mock to timetravel in unit tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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