Search in sources :

Example 11 with TestScheduler

use of rx.schedulers.TestScheduler in project AnDevCon-RxPatterns by colintheshots.

the class Example16Test method using_testscheduler_to_simulate_network_events.

@Test
public void using_testscheduler_to_simulate_network_events() {
    // TestScheduler lets you advance time by hand
    TestScheduler scheduler = Schedulers.test();
    TestSubscriber<NetworkResponse> subscriber = new TestSubscriber<>();
    // Scheduler.Worker lets you schedule events in time
    Scheduler.Worker worker = scheduler.createWorker();
    // Subjects allow both input and output, so they can be swapped in for
    // Retrofit calls to unit test your code.
    final PublishSubject<NetworkResponse> networkSubject = PublishSubject.create();
    // schedule a first observable event to occur at 1000 ms
    worker.schedule(new Action0() {

        @Override
        public void call() {
            // explicitly calling onNext in a worker allows one to
            // create a very specific test of timed events
            networkSubject.onNext(new NetworkResponse(401));
        }
    }, 1000, TimeUnit.MILLISECONDS);
    // schedule a second observable event to occur at 2000 ms
    worker.schedule(new Action0() {

        @Override
        public void call() {
            networkSubject.onNext(new NetworkResponse(200));
            networkSubject.onCompleted();
        }
    }, 2000, TimeUnit.MILLISECONDS);
    // we must subscribe before anticipating results
    networkSubject.subscribeOn(scheduler).subscribe(subscriber);
    // we can manually advance time using the scheduler and check assertions
    scheduler.advanceTimeBy(1500, TimeUnit.MILLISECONDS);
    subscriber.assertReceivedOnNext(Arrays.asList(new NetworkResponse(401)));
    // awaitTerminalEvent will wait forever if we don't advance time enough
    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    subscriber.awaitTerminalEvent();
    subscriber.assertReceivedOnNext(Arrays.asList(new NetworkResponse(401), new NetworkResponse(200)));
    // TestSubscriber provides many useful methods
    subscriber.assertNoErrors();
    subscriber.assertValueCount(2);
    subscriber.assertUnsubscribed();
}
Also used : Action0(rx.functions.Action0) TestScheduler(rx.schedulers.TestScheduler) Scheduler(rx.Scheduler) TestSubscriber(rx.observers.TestSubscriber) TestScheduler(rx.schedulers.TestScheduler) Override(java.lang.Override) Test(org.junit.Test)

Aggregations

TestScheduler (rx.schedulers.TestScheduler)11 Test (org.junit.Test)8 TestSubscriber (rx.observers.TestSubscriber)6 Override (java.lang.Override)3 List (java.util.List)3 Before (org.junit.Before)3 Scheduler (rx.Scheduler)2 Action0 (rx.functions.Action0)2 KSRobolectricTestCase (com.kickstarter.KSRobolectricTestCase)1 Environment (com.kickstarter.libs.Environment)1 Long (java.lang.Long)1 ArrayList (java.util.ArrayList)1 TimeUnit (java.util.concurrent.TimeUnit)1 TimeoutException (java.util.concurrent.TimeoutException)1