Testing RxJava: AdvanceTime not working in simple deferred flowable

Viewed 123

I have a very simple function that defers a value with a given delay:

Flowable.defer<Effect> { Flowable.just(Effect.Success) as Publisher<out Effect> }
  .delay(2, TimeUnit.SECONDS)
  .subscribeOn(computationScheduler)
  .observeOn(mainScheduler)

I try to test it advancing the time in the computationScheduler like this:

  private val mainScheduler = Schedulers.trampoline()
  private val computationScheduler = TestScheduler()

  @Test
  fun solve() {
    val testObserver = actor.invoke(Action.Solve).test()

    computationScheduler.advanceTimeBy(3, TimeUnit.SECONDS)

    testObserver.assertValues(Effect.Success)
  }

Without the delay, this just works, but it seems I can't manage to advance the time properly. Thanks in advance for your help

1 Answers

According to the javadocs of the delay method you are calling:

This version of {@code delay} operates by default on the {@code computation} {@link Scheduler}.

So your code is not working because the delay method is using a different computation scheduler than the one you are subscribing to.

In order to fix it you have to either pass your TestScheduler computationScheduler to the delay method:

Flowable.defer<Effect> { Flowable.just(Effect.Success) as Publisher<out Effect> }
    .delay(2, TimeUnit.SECONDS, computationScheduler)
    ...

Or set the computation scheduler handler of the rxjava lib:

RxJavaPlugins.setComputationSchedulerHandler { computationScheduler }
Related