Tuesday, July 4, 2017

Testing for Exceptions in RxJava 2.x

RxJava 2.x provides useful assertions to test for exception conditions. Assume we have the following class with three methods that result in three different error conditions
  1. No Error
  2. An exception
  3. An exception with a distinct property, in this case an exception message.

We can write one test for each of the three error conditions by using the different asserts available in RxJava
  1. assertNoErrors() 
  2. assertError(Class<? extends Throwable> errorClass)
  3. assertError(Throwable error)
  4. assertError(Predicate<Throwable> errorPredicate)
The ability to write custom errorPredicate is extremely useful when the same exception type is thrown from several locations but each exception instance can have a different property such as the exception message.