A Clock
is meant for providing access to the current instant, date and time using a time-zone. You don't really need to mock it. As your class needs to obtain the current instant, so it should receive an instance of the Clock
in the constructor:
public class FooService {
private final Clock clock;
public FooService(Clock clock) {
this.clock = clock;
}
public boolean isLocked() {
long differenceInSecond = (clock.millis() - this.getLockedAt()) / 1000;
return differenceInSecond < 7200;
}
private long getLockedAt() {
...
}
}
Then, in your test, you can use a fixed()
clock, which will always return the same instant:
@Test
public void isLocked_shouldReturnTrue_whenDifferenceInSecondIsSmallerThan7200() {
// Create a fixed clock, which will always return the same instant
Instant instant = Instant.parse("2020-01-01T00:00:00.00Z");
Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
// Create a service instance with the fixed clock
FooService fooService = new FooService(clock);
// Invoke the service method and then assert the result
boolean locked = fooService.isLocked();
assertThat(locked).isTrue();
}
In a Spring Boot application, you could expose a Clock
as a @Bean
:
@Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
And then Spring will take care of injecting it into your service:
@Service
public class FooService {
private final Clock clock;
public FooService(Clock clock) {
this.clock = clock;
}
...
}