Test RxJava2 PublishSubject the right way

Julien Veneziano
Fueled Engineering
Published in
1 min readApr 5, 2018

I was recently writing a unit test for a PublishSubject and was not able to write a valid test despite the code working well in the application.

The problem

I wrote the following test:

Running the test above failed and the value variable was not changed. It was puzzling for me because the steps of the tests are straightforward:

  • Initialize the Rx chain by calling myRxFunction
  • Push the new String in the chain with onNext
  • Trigger the action in the TestScheduler
  • Make sure the variable is update

What went wrong?

After banging my head against the wall I realized the problem lied with the timing. In short, I was pushing my string in the Rx chain before the chain was ready to receive it.

The solution

Call TestScheduler.triggerAction() before onNext()!

Good developers write good code, and great developers test their good code.

--

--