Understanding TestScheduler

Think of an Observable/Flowable created with the Observable.interval() / Flowable.interval() factory method. If you have given a long interval (say five minutes) in them and have tested at least say 100 emissions then it would take a long time for testing to complete (500 minutes = 8.3 hours, that is, a complete man-hour just to test a single producer). Now if you have more producers like that with a larger interval and more emissions to test then it would probably take the whole lifetime to test, when would you ship the product then?

TestScheduler is here to save your life. They can effectively simulate time with time-driven producers so that we can do assertions by fast-forwarding it by a specific amount.

So, the following is the respective implementation:

    @Test 
    fun `test by fast forwarding time`() { 
      val testScheduler = TestScheduler() 
 
      val observable = 
Observable.interval(5,TimeUnit.MINUTES,testScheduler) val testObserver = TestObserver<Long>() observable.subscribe(testObserver) testObserver.assertSubscribed() testObserver.assertValueCount(0)//(1) testScheduler.advanceTimeBy(100,TimeUnit.MINUTES)//(2) testObserver.assertValueCount(20)//(3) testScheduler.advanceTimeBy(400,TimeUnit.MINUTES)//(4) testObserver.assertValueCount(100)//(5) }

So, here we created an Observable with Observable.interval with a 5 minute interval and TestScheduler as its Scheduler.

On comment (1), it should not receive any emissions (as there are still 5 minutes before it should receive its first emission) and we are testing it with assertValuesCount(0).

We then fast-forwarded the time by 100 minutes on comment (2), and tested whether we received 20 emissions on comment (3). TestScheduler provides us with the advanceTimeBy method, which takes a timespan and unit as parameters and simulates that for us.

We then fast-forwarded time by another 400 minutes and tested if we received a total of 100 emissions on comment (4) and comment (5).

As you would expect, the test passes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.20