loading...
Cover image for Matt's Tidbits #68 - Testing RxJava Observables

Matt's Tidbits #68 - Testing RxJava Observables

mpeng3 profile image Matthew Groves Originally published at Medium ・2 min read

Last week I shared some tips about working from home. This time, I want to tell you about testing RxJava Observables.

Recently, I wanted to write a unit test that verified that a particular Observable had been subscribed to. I did a little quick Googling and came across the following:
http://reactivex.io/RxJava/javadoc/rx/subjects/TestSubject.html

However, when I tried to use this in my project, I couldn't find it! A little more searching turned up this document:
https://github.com/ReactiveX/RxJava/wiki/What%27s-different-in-2.0#testsubject

Because my project is using RxJava 2, TestSubject was not available because it has been deprecated.

I then discovered that the PublishSubject I have often used when unit testing Observables has a handy method: hasObservers()

However, I wanted to point out one possible source of confusion. The RxJava 1->2 migration document says:

The 1.x TestSubject has been dropped. Its functionality can be achieved via TestScheduler, PublishProcessor/PublishSubject and observeOn(testScheduler)/scheduler parameter.

The example code they provide shows calling the .test() method on the PublishSubject.

WARNING
If you do this, hasObservers() will always return true, as calling .test() on your PublishSubject is effectively subscribing to it, so it will by default have an Observer.

So, if you are trying to test that an Observable has been subscribed to (in my case, as a result of calling some other Observable) - only call .test() on the outer Observable. Then you can call hasObservers() on the secondary Observable you have passed in to verify that the outer one has subscribed to it.

What special strategies do you use for testing RxJava code? Leave a comment below! And, please follow me on Medium if you're interested in being notified of future tidbits.

This tidbit was originally delivered on May 8, 2020.

Posted on by:

mpeng3 profile

Matthew Groves

@mpeng3

Software engineer with 10+ years of professional experience in C++, C#, Java, and Kotlin.

Discussion

markdown guide