Skip to content

Instantly share code, notes, and snippets.

@bholota
Created November 27, 2017 15:44
Show Gist options
  • Save bholota/c28c716c8e3d036e175645c78312fb13 to your computer and use it in GitHub Desktop.
Save bholota/c28c716c8e3d036e175645c78312fb13 to your computer and use it in GitHub Desktop.
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