I'm creating unit tests for my RxJava observables in Android.
I want to chain return values from a mock and simulate error/resume values in a observable.
I'm doing this:
when(repository.getObservable())
.thenReturn(Observable.error(new Exception()))
.thenReturn(Observable.just(driver));
My observable:
return repository.getObservable()
.retryWhen(observale -> {
return observable
.zipWith(Observable.range(1, 3), Pair::create)
.flatMap(o -> {
if (o.second < count) {
return Observable.timer(1000, TimeUnit.MILLISECONDS);
}
return Observable.error(o.first);
})))
But I only receive the Observable.error(new Exception())
, even calling the retryWhen
method 3+ times.
Did somebody know how can I test the re-emission of a different observable to test the retryWhen
operator?
retryWhen()
won't call repository.getObservable()
a second time. Instead, it takes the Observable.error()
that was returned the first time and resubscribes to it.
In order to use retryWhen()
in this way, you'd have to return a single Observable
that returns an error the first time it's subscribed to and does not do so in subsequent subscriptions. For example, you could do something like this:
Observable.defer(new Func0<Observable<String>>() {
boolean hasBeenSubscribedTo = false;
@Override public Observable<String> call() {
if (!hasBeenSubscribedTo) {
hasBeenSubscribedTo = true;
return Observable.error(new Exception());
}
return Observable.just("Hello, world!");
}
})
.retryWhen(/* ...etc... */)