DEV Community

Cover image for Matt's Tidbits #68 - Testing RxJava Observables
Matthew Groves
Matthew Groves

Posted on • Originally published at Medium

Matt's Tidbits #68 - Testing RxJava Observables

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.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay