延迟测试单元测试Rxjava可观察对象 [英] Unit testing Rxjava observables that have a delay
问题描述
我希望能够对发射延迟的Observable
进行单元测试,但无需实际等待延迟时间.有没有办法做到这一点?
I want to be able to unit test an Observable
that has a delayed emission, but without actually waiting for the delay time. Is there a way to do this?
我目前正在使用CountDownHatch来延迟断言,它可以正常工作,但是会增加测试运行时间.
I'm currently using a CountDownHatch to delay the assert, and that works fine, but increases the test run time.
示例:
val myObservable: PublishSubject<Boolean> = PublishSubject.create<Boolean>()
fun myObservable(): Observable<Boolean> = myObservable.delay(3, TimeUnit.SECONDS)
@Test
fun testMyObservable() {
val testObservable = myObservable().test()
myObservable.onNext(true)
// val lock = CountDownLatch(1)
// lock.await(3100, TimeUnit.MILLISECONDS)
testObservable.assertValue(true)
}
推荐答案
由于@ aaron-he的回答,我得以提出一个完整的解决方案.
I was able to come up with a complete solution thanks to @aaron-he's answer.
它使用TestScheduler
组合来延长时间,还使用RxJavaPlugins
组合来使用testScheduler覆盖默认调度程序.这样就可以测试myObservable()
函数,而无需进行修改或需要传入Scheduler
.
It uses a combination of TestScheduler
to advance the time and also RxJavaPlugins
to override the default scheduler with the testScheduler. This allowed testing the myObservable()
function without modification or needing to pass in a Scheduler
.
@Before
fun setUp() = RxJavaPlugins.reset()
@After
fun tearDown() = RxJavaPlugins.reset()
@Test
fun testMyObservable() {
val testScheduler = TestScheduler()
RxJavaPlugins.setComputationSchedulerHandler { testScheduler }
val testObservable = myObservable().test()
myObservable.onNext(true)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
testObservable.assertEmpty()
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
testObservable.assertValue(true)
}
这篇关于延迟测试单元测试Rxjava可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!