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();
}
Aggregations