【发布时间】:2020-09-21 18:31:42
【问题描述】:
我正在尝试使用SchedulerClock 而不是System.currentTimeMillis() 或传入普通的Clock 作为模拟,因为我希望我可以使用reactor 的虚拟时间测试功能,但它似乎不像我那样工作预计会的。
我在这里做错了吗?如何在我的代码中获得“虚拟”时间以更好地进行测试?
@Test
void testVirtualTimeWithSchedulerClock() {
Flux<Integer> records = Flux.just(1, 2, 3, 4);
List<Long> latencies = new ArrayList<>();
StepVerifier.withVirtualTime(() -> {
Clock clock = SchedulerClock.of(Schedulers.immediate());
long start = clock.millis();
return records.delayElements(Duration.ofSeconds(1))
.doOnNext(r -> {
long now = clock.millis();
long latency = now - start;
latencies.add(latency);
});
})
.expectSubscription()
.expectNoEvent(Duration.ofSeconds(1))
.expectNext(1)
.expectNoEvent(Duration.ofSeconds(1))
.expectNext(2)
.expectNoEvent(Duration.ofSeconds(1))
.expectNext(3)
.thenAwait(Duration.ofSeconds(1))
.expectNext(4)
.expectComplete()
.verify(VERIFIER_TIMEOUT);
assertEquals(ImmutableList.of(1000L, 2000L, 3000L, 4000L), latencies);
// FAIL: expected: <[1000, 2000, 3000, 4000]> but was: <[53, 53, 53, 53]>
}
【问题讨论】:
标签: java unit-testing time project-reactor