RxJava 2 overriding IO scheduler in unit test

前端 未结 4 1992
你的背包
你的背包 2021-02-02 13:28

I\'m trying to test the following RxKotlin/RxJava 2 code:

validate(data)
    .subscribeOn(Schedulers.io())
    .observeO         


        
4条回答
  •  离开以前
    2021-02-02 14:13

    As an alternative to proposed solutions, this has been working fine for a while in my projects. You can use it in your test classes like this:

    @get:Rule
    val immediateSchedulersRule = ImmediateSchedulersRule()
    

    And the class looks like this:

    class ImmediateSchedulersRule : ExternalResource() {
    
        val immediateScheduler: Scheduler = object : Scheduler() {
    
            override fun createWorker() = ExecutorScheduler.ExecutorWorker(Executor { it.run() })
    
            // This prevents errors when scheduling a delay
            override fun scheduleDirect(run: Runnable, delay: Long, unit: TimeUnit): Disposable {
                return super.scheduleDirect(run, 0, unit)
            }
    
        }
    
        override fun before() {
            RxJavaPlugins.setIoSchedulerHandler { immediateScheduler }
            RxJavaPlugins.setComputationSchedulerHandler { immediateScheduler }
            RxJavaPlugins.setNewThreadSchedulerHandler { immediateScheduler }
    
            RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediateScheduler }
            RxAndroidPlugins.setMainThreadSchedulerHandler { immediateScheduler }
        }
    
        override fun after() {
            RxJavaPlugins.reset()
        }
    
    }
    

    You can find a way to migrate from TestRule to ExternalResource here and get more info on testing RxJava 2 here.

提交回复
热议问题