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().isEmpty()); Assert.assertTrue(subscriber.isUnsubscribed()); }
The test is, again, very simple. We create a TestSubscriber
instance and subscribe to the tested Observable
instance with it. And we have access to the whole state after the Observable
instance is completed. Let's take a look at the following term list:
getOnNextEvents()
method, we are able to retrieve all the items emitted by the Observable
instance and compare them to the expected List
variable.getOnCompletedEvents()
method, we are able to inspect the OnCompleted notification and to check if it was sent at all. For example, the Observable.never()
method doesn't send it.getOnErrorEvents()
method, we are able to inspect OnError notifications if there were any. In this case, we assert that there were no errors.isUnsubscribed()
method, we can assert that, after everything completed, our Subscriber
instances were unsubscribed.The TestSubscriber
instance has some assertion methods too. So, there is one more way in which the test could be written:
@Test public void testUsingTestSubscriberAssertions() { TestSubscriber<String> subscriber = new TestSubscriber<String>(); tested.subscribe(subscriber); subscriber.assertReceivedOnNext(expected); subscriber.assertTerminalEvent(); subscriber.assertNoErrors(); subscriber.assertUnsubscribed(); }
These are almost the same assertions, but done with the TestSubscriber
instance's own assert*
methods.
The source code for the preceding test can be found at https://github.com/meddle0x53/learning-rxjava/blob/master/src/test/java/com/packtpub/reactive/chapter07/SortedObservableTest.java—these are the third and the fourth test methods.
With these techniques, we can test different behaviors and states of our RxJava
logic. There is one last thing left to learn in this chapter—testing asynchronous Observable
instances, such as the ones created by the Observable.interval()
method.
18.119.104.95