我有一个验证日期过期的服务:
@RequiredArgsConstructor
public class ExpirationVerificationService {
private final Clock clock;
public boolean hasPassed(Instant instant) {
return Instant.now(clock).isAfter(instant);
}
}我想验证一下,随着时间的推移,hasPassed是否返回不同的值:
public class ExpirationVerificationServiceTest {
private ExpirationVerificationService service;
private Clock clock;
@BeforeEach
public void init() {
clock = Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"));
service = new ExpirationVerificationService(clock);
}
@Test
public void testHasExpired() {
Instant instant = Instant.now(clock).plus(Duration.ofDays(30);
assertFalse(service.hasPassed(instant));
// TODO move clock to future
assertTrue(service.hasPassed(instant));
}
}如何将Clock实例的内部状态更新为将来的状态?
注意:我正在测试的实际业务逻辑比本例复杂得多(验证来自数据库的Oauth令牌的过期时间),我不能只使用过去的不同Instant实例。
发布于 2020-10-20 01:01:55
Clock实际上只是一个Instant的提供者。您可以简单地声明一个固定时钟,如下所示:
Instant fixedInstant = Instant.EPOCH;
Clock clock = () -> fixedInstant;因此,如果你想要一个可设置的Clock,你可以声明:
AtomicReference<Instant> theInstant = new AtomicReference<>(Instant.EPOCH);
Clock clock = () -> theInstant.get();然后更新theInstant。
https://stackoverflow.com/questions/64431899
复制相似问题