Skip to content

Instantly share code, notes, and snippets.

@EarlOfEgo
Created January 31, 2017 08:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EarlOfEgo/f023c1b1d2876ada2efae6b2befd6323 to your computer and use it in GitHub Desktop.
Save EarlOfEgo/f023c1b1d2876ada2efae6b2befd6323 to your computer and use it in GitHub Desktop.
A test rule for unit test to override all schedulers with trampoline
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* Test rule that overrides all schedulers with the trampoline scheduler.
* This means everything runs on the same thread, when using this rule
*/
class Rx2SchedulersOverrideRule : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
@Throws(Throwable::class)
override fun evaluate() {
//Set Scheduler for AndroidSchedulers
RxAndroidPlugins.reset()
RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() }
//Set Schedulers to trampoline
RxJavaPlugins.reset()
RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() }
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() }
base.evaluate()
RxAndroidPlugins.reset()
RxJavaPlugins.reset()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment