Using the TestSubscriber class for in-depth testing

The TestSubscriber instance is a special Subscriber instance, which we can pass to the subscribe() method of any Observable instance.

We can retrieve all the received items and notifications from it. We can also look at the last thread on which the notifications have been received and the subscription state.

Let's rewrite our test using it, in order to demonstrate its capabilities and what it stores:

@Test
public void testUsingTestSubscriber() {
  TestSubscriber<String> subscriber =
    new TestSubscriber<String>();
  tested.subscribe(subscriber);
  Assert.assertEquals(expected, subscriber.getOnNextEvents());
  Assert.assertSame(1, subscriber.getOnCompletedEvents().size());
  Assert.assertTrue(subscriber.getOnErrorEvents() ...

Get Learning Reactive Programming with Java 8 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.