Created
November 27, 2017 15:44
-
-
Save bholota/c28c716c8e3d036e175645c78312fb13 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.some.app.common | |
import io.reactivex.Scheduler | |
import io.reactivex.android.plugins.RxAndroidPlugins | |
import io.reactivex.internal.schedulers.ExecutorScheduler | |
import io.reactivex.plugins.RxJavaPlugins | |
import io.reactivex.schedulers.TestScheduler | |
import org.junit.rules.TestRule | |
import org.junit.runner.Description | |
import org.junit.runners.model.Statement | |
/** | |
* After applying such rule in unit test it will replace default schedulers via plugins api | |
* | |
* This class is especially helpful when testing streams with operators that have default schedulers | |
* like [io.reactivex.Observable.delay] | |
*/ | |
class TestSchedulerRule : TestRule { | |
private val immediate = object : Scheduler() { | |
override fun createWorker(): Worker { | |
return ExecutorScheduler.ExecutorWorker(Runnable::run) | |
} | |
} | |
val testScheduler = TestScheduler() | |
override fun apply(base: Statement?, description: Description?): Statement { | |
return object : Statement() { | |
override fun evaluate() { | |
RxJavaPlugins.setIoSchedulerHandler { testScheduler } | |
RxJavaPlugins.setComputationSchedulerHandler { testScheduler } | |
RxJavaPlugins.setNewThreadSchedulerHandler { testScheduler } | |
RxAndroidPlugins.setMainThreadSchedulerHandler { immediate } | |
try { | |
base?.evaluate() | |
} finally { | |
RxJavaPlugins.reset() | |
RxAndroidPlugins.reset() | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment