使用虚拟时间测试基于时间的反应堆堆芯流
Reactor Core實現了Reactive Streams規范,并處理了(可能無限的)數據流。 如果您感興趣,請查看它提供的出色文檔 。 在這里,我假設對Reactor Core庫的Flux和Mono類型有一些基本的了解,并且將介紹Reactor Core提供了對時間本身的抽象,從而可以測試依賴于時間的函數。
對于某些Reactor核心運營商來說,時間是一個重要的考慮因素-例如,“間隔”功能的一種變體,它在初始“延遲” 10秒后每5秒發出一個遞增的數字:
val flux = Flux.interval(Duration.ofSeconds(10), Duration.ofSeconds(5)).take(3)根據正常時間流逝測試這樣的數據流將是可怕的,這樣的測試大約需要20秒才能完成。
Reactor-Core提供了一種解決方案,一種對時間本身的抽象-基于虛擬時間的調度程序,它提供了一種確定性的方式來測試這些類型的操作的巧妙方法。
讓我以兩種方式展示它,一種明確的方式應該使基于虛擬時間的調度程序的動作非常清晰,然后再推薦使用Reactor Core進行測試的方法。
import org.assertj.core.api.Assertions.assertThat import org.junit.Test import reactor.core.publisher.Flux import reactor.test.scheduler.VirtualTimeScheduler import java.time.Duration import java.util.concurrent.CountDownLatchclass VirtualTimeTest {@Testfun testExplicit() {val mutableList = mutableListOf<Long>()val scheduler = VirtualTimeScheduler.getOrSet()val flux = Flux.interval(Duration.ofSeconds(10), Duration.ofSeconds(5), scheduler).take(3)val latch = CountDownLatch(1)flux.subscribe({ l -> mutableList.add(l) }, { _ -> }, { latch.countDown() })scheduler.advanceTimeBy(Duration.ofSeconds(10))assertThat(mutableList).containsExactly(0L)scheduler.advanceTimeBy(Duration.ofSeconds(5))assertThat(mutableList).containsExactly(0L, 1L)scheduler.advanceTimeBy(Duration.ofSeconds(5))assertThat(mutableList).containsExactly(0L, 1L, 2L)latch.await()}}1.首先,將“ Flux.interval”功能的計劃程序設置為基于虛擬時間的計劃程序。
2.預計在10秒延遲后每5秒發射一次數據流
3. VirtualTimeScheduler提供了一種“ advanceTimeBy”方法來將虛擬時間提前一個持續時間,因此該時間將首先提前10秒的延遲時間,屆時將發出第一個元素(0)。
4.然后將其前進5秒鐘兩次,分別得到1和2。
這是確定性的,測試可以快速完成。 但是,此版本的測試很丑陋,它使用列表來收集和聲明結果,并使用CountDownLatch控制何時終止測試。 測試Reactor-Core類型的一種更為簡潔的方法是使用出色的StepVerifier類,并且使用該類的測試如下所示:
import org.junit.Test import reactor.core.publisher.Flux import reactor.test.StepVerifier import reactor.test.scheduler.VirtualTimeScheduler import java.time.Durationclass VirtualTimeTest {@Testfun testWithStepVerifier() {VirtualTimeScheduler.getOrSet()val flux = Flux.interval(Duration.ofSeconds(10), Duration.ofSeconds(5)).take(3)StepVerifier.withVirtualTime({ flux }).expectSubscription().thenAwait(Duration.ofSeconds(10)).expectNext(0).thenAwait(Duration.ofSeconds(5)).expectNext(1).thenAwait(Duration.ofSeconds(5)).expectNext(2).verifyComplete()}}借助StepVerifier進行的這項新測試可以很好地理解每步前進的時間,并斷言當時的期望值。
翻譯自: https://www.javacodegeeks.com/2017/09/testing-time-based-reactor-core-streams-virtual-time.html
總結
以上是生活随笔為你收集整理的使用虚拟时间测试基于时间的反应堆堆芯流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jclouds_使用jclouds在S3
- 下一篇: 镯组词 镯组词有哪些