简体   繁体   中英

Chain different return in Mockito for retryWhen call

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... */)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM