Unit testing Rxjava observables that have a delay

TestScheduler is perfect for this. It has a handy method advanceTimeBy(long, TimeUnit) allows you to control the timing. And Observable.delay has an overload method takes a Scheduler.

So just use the default Scheduler.computation() in the myObservable function, and use TestScheduler for unit testing.


I was able to come up with a complete solution thanks to @aaron-he's answer.

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)
}