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!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay