R. Zagórski
R. Zagórski

Reputation: 20268

RxJava test Observable

There is something like TestSubscriber. It has very useful functions like awaitTerminalEvent(), getOnNextEvents(), etc.

Is there an equivalent of TestSubscriber for Observable that might be pinned to some observable in the middle of sequence?

I would like to test some specific cases, one of which is:

Each of those cases require workarounds like:

observable
  .doOnNext(o -> {
      // Observable was given a value
   });

If there is no nice way already available, how to make the call above cleaner?

Upvotes: 1

Views: 427

Answers (1)

Dave Moten
Dave Moten

Reputation: 12097

Assertions need to be tested outside of the lambdas that are part of the observable because the lambdas themselves may never run (like in your onErrorResumeNext case). So you need some object defined outside of the observable to carry the result that we want to test.

A common technique for testing observables is to use Atomic objects to record events:

AtomicBoolean executed = new AtomicBoolean(false);
Observable
  .empty()
  .doOnNext(t -> executed.set(true))
  .subscribe();
assertFalse(executed.get());

This example could be better done with TestSubscriber but it shows the technique.

rxjava-extras has convenience classes if you are using java 6 (heck just use retrolambda) so that you don't need to write anonymous classes for this use case:

AtomicBoolean executed = new AtomicBoolean(false);
Observable
  .empty()
  .doOnNext(Actions.setToTrue(executed))
  .subscribe();
assertFalse(executed.get());

Upvotes: 1

Related Questions