延迟测试单元测试Rxjava可观察对象 [英] Unit testing Rxjava observables that have a delay

查看:85
本文介绍了延迟测试单元测试Rxjava可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够对发射延迟的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆