Testing RxJava code made easy

Niklas Baudy
2 min readDec 9, 2017

There’s a nice little hidden treasure in RxJava 2 that was also backported to RxJava 1. It’s the test() function that allows you to easily test RxJava 2 streams. It has a bunch of useful assertions that we’ll dive into.

Let’s take an easy example. We want to assert that an Observable is being subscribed to, emits one value, completes and has no errors.

Observable.just(1)
.test()
.assertSubscribed()
.assertValues(1)
.assertComplete()
.assertNoErrors()

It’s quite a lot of statements that we need to do here. Luckily there’s assertResult()

Observable.just(1)
.test()
.assertResult(1)

It’ll do all of the above for us already. It also works for Completable, Maybe and Single.

Completable.complete()
.test()
.assertResult()
Maybe.empty<Int>()
.test()
.assertResult()
Maybe.just(1)
.test()
.assertResult(1)
Single.just(1)
.test()
.assertResult(1)

As a matter of fact all of those functions outlined here in this article will work on any RxJava 2 reactive type since they share the same test infrastructure.

Let’s say we want the same assertions but with the difference that we don’t want the stream to be completed yet so that it could emit more data. There’s assertValuesOnly for us:

Observable.create<Int> { it.onNext(1) }
.test()
.assertValuesOnly(1)

--

--