我一直在使用 lite-rx-api-hands-on尝试了解 Reactor 的教程,我对其中一项测试的结果有点困惑,尝试使用 StepVerifier 进行虚拟时间。
这非常有效:
@Test
public void expect10Elements() {
StepVerifier.withVirtualTime(() -> Flux.interval(Duration.ofSeconds(1)).take(10))
.thenAwait(Duration.ofSeconds(10))
.expectNextCount(10)
.expectComplete()
.verify();
}
但这行不通
@Test
public void expect10Elements() {
Flux<Long> flux = Flux.interval(Duration.ofSeconds(1)).take(10);
StepVerifier.withVirtualTime(() -> flux)
.thenAwait(Duration.ofSeconds(10))
.expectNextCount(10)
.expectComplete()
.verify();
}
如果我在发布者中发布之前没有订阅通量,我不太明白为什么会发生这种情况。有人可以帮忙吗?
最佳答案
这是因为虚拟时间的实现方式。
有关解释,请参阅Reactor Reference :
This virtual time feature plugs in a custom Scheduler in Reactor’s Schedulers factory. Since these timed operators usually use the default Schedulers.parallel() scheduler, replacing it with a VirtualTimeScheduler does the trick. However, an important prerequisite is that the operator be instantiated after the virtual time scheduler has been activated.
To increase the chances that this happens correctly, the StepVerifier does not take a simple Flux as input. withVirtualTime takes a Supplier, which guides you into lazily creating the instance of the tested flux after having done the scheduler set up.
Take extra care to ensure the
Supplier<Publisher<T>>
can be used in a lazy fashion. Otherwise, virtual time is not guaranteed. Especially avoid instantiating the Flux earlier in the test code and having the Supplier return that variable. Instead, always instantiate the Flux inside the lambda.
关于java - 为什么 StepVerifer 虚拟时间不适用于 Flux?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60576916/