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:
However, when I tried to use this in my project, I couldn't find it! A little more searching turned up this document:
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:
However, I wanted to point out one possible source of confusion. The RxJava 1->2 migration document says:
TestSubject has been dropped. Its functionality can be achieved via
The example code they provide shows calling the
.test() method on the
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.