Testing timeout handling TestSubject and TestScheduler

554 views
Skip to first unread message

Olve Hansen

unread,
Oct 14, 2014, 4:18:55 PM10/14/14
to rxj...@googlegroups.com
public static <T extends PlayEvent> void timeoutAndDistinctViewingSession(
            Observable<T> source, Observer<T> sink
    ) {
        source.timeout(/*Timeout after delay after last event,
         and preventing memory leaks so that inactive streams are closed */
                       3, TimeUnit.HOURS
        )
              .distinctUntilChanged(/*So that consecutive identical play events are skipped*/
                                    PlayEvent::getViewingSession
              )
              .serialize()
              .subscribe(sink /*Pass event on to function/class responsible for deciding if this is  a kick*/);
    }

I have this Observable setup, and I want to test how my "sink" behaves when the source times out. I try to do this with this unit test:

@Test
    public void testTimeoutWindow() throws Exception {

        final TestScheduler testScheduler = Schedulers.test();
        TestSubject<PlayEvent> testSubject = TestSubject.create(testScheduler);

        PlayEventRxFunctions.timeoutAndDistinctViewingSession(testSubject, this);

        final int userId = 1;
        testSubject.onNext(createPlayEvent(userId, UUID.randomUUID()));
        testScheduler.advanceTimeBy(4, TimeUnit.HOURS);
        testSubject.onNext(createPlayEvent(userId, UUID.randomUUID()));

        Assertions.assertThat(getOnErrorEvents().size()).isEqualTo(1);
        Assertions.assertThat(getOnNextEvents().size()).isEqualTo(1);
    }

Although it does not work when I advance the time using test scheduler.

 am very new to RxJava, and this might be a big misunderstanding on how things should work on my part...

Would be grateful for any pointers on how to test this setup could be tested!

Regards!

Ben Christensen

unread,
Oct 14, 2014, 8:17:06 PM10/14/14
to Olve Hansen, rxj...@googlegroups.com
The TestScheduler needs to be passed into the timeout operator as well for it to use virtual time. 

Ben Christensen
@benjchristensen

Olve Hansen

unread,
Oct 15, 2014, 1:43:03 AM10/15/14
to rxj...@googlegroups.com, olv...@gmail.com
Of course, now that is really obvious. Thanks! :-)
Reply all
Reply to author
Forward
0 new messages