Wednesday, June 19, 2019

Learning RxJava: Thoughts on Chapter 10

Testing and Debugging

Blocking Subscribers and Operators


There are blocking subscribers and operators that can be used to ensure the test waits until you get your results from the chain so that you can run your tests against them. While these can be useful in tests, frequently the TestObserver and TestSubscriber are better choices. Note that while it can be tempting to use blocking subscribers and operators in production code, you should avoid doing so, because it limits the effectiveness and flexibility of your reactive code.

TestObserver and TestSubscriber


TestObserver (for Observables) and TestSubscriber (for Flowables) make for very powerful and flexible tools for writing unit tests. They will keep track of data related to emissions, errors, and completion events, which allows you to examine and assert this data afterwards. They even have assertion methods built into them, such as assertValueCount, assertValues, etc.

TestScheduler


The TestScheduler is a special scheduler that allows you to manipulate time for testing purposes. It has methods such as advanceTimeBy and advanceTimeTo that will allow you to test time bound code quickly. The book does note that the TestScheduler  "is not a thread-safe Scheduler and should not be used with actual concurrency." If the code that you wish to test doesn't allow easy access to setting the Scheduler, you can instead use RxJavaPlugins.setComputationScheduler() or other such methods that will override the standard Schedulers and inject the TestScheduler in its place.

Debugging Strategies


Debugging Rx code can be difficult, since frequently the stack traces can be less than useful and it can sometimes be difficult to apply breakpoints where you need them, but a strategy that can work well is to take advantage of the doOnNext operator and other similar operators to be able to see what's going on at every step of the chain and to track down where the faulty link in the chain is located.