这是一个简单的测试示例,展示了什么时候以及为什么会失败。简而言之,我模拟了
在实际情况中,服务类使用
所以你可以看到,即使我嘲笑
Instance
类的静态now()
方法,但后来又调用了这个被模拟的实例的另一个方法-minus()
,它将返回null
。@Test
void givenInstantMock_whenNow_thenGetFixedInstant() {
String instantExpected = "2014-12-22T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
Instant instant = Instant.now(clock);
try (MockedStatic<Instant> mockedStatic = mockStatic(Instant.class)) {
mockedStatic.when(Instant::now).thenReturn(instant);
Instant now = Instant.now();
assertThat(now.toString()).isEqualTo(instantExpected);
Instant earlier2weeks = now.minus(Period.ofWeeks(2));
assertNotNull(earlier2weeks);// FAILS as it will be null
}
}
在实际情况中,服务类使用
Instant::now
创建一个新的Instant。//in a component class
@Component
class DeletionScheduler {
...
public void findOutdatedEntries() {
Instant limitDate = Instant.now().minus(validityGracePeriod);
List<Entry> entriedToDelete= shareService.findOutdatedEtriees(limitDate );
...
}
所以你可以看到,即使我嘲笑
Instant.now()
,对这个实例调用minus
总是会返回NULL。So the idea of the test was:
- to create an entry with a `limitDate` in the future.
- trick/mock the System clock to be in the future
- check if there are some outdated entries.
Is there any way to get around it?