blitzqwe
blitzqwe

Reputation: 2040

Retry in rxJava

I want to test the retry in the code:

public Observable<Foo> getFoo() {
        return barService.getBar()
                .retry(3)
                .map(barToFoo);
}

and the unit test:

//given
barService = Mockito.mock(BarService.class)
PublishSubject<Bar> barSubject= PublishSubject.create();
when(barService.getBar()).thenReturn(barSubject);

TestSubscriber<Foo> fooProbe= new TestSubscriber<>();
getFoo().subscribe(fooProbe);

//when
barSubject.onError(new RuntimeException("bar exception"));
barSubject.onNext(new Bar())

//then
fooProbe.assertNoErrors();
fooProbe.assertValue(new Bar());

fails with java.lang.AssertionError: Unexpected onError events: 1

Upvotes: 0

Views: 819

Answers (1)

akarnokd
akarnokd

Reputation: 69997

Calling onError or onCompleted brings the Subjects into a terminal state and no further events are accepted/relayed.

Generally, you can't do retry with Subjects but you can try with fromCallable and a counter:

AtomicInteger count = new AtomicInteger();
Observable<Bar> o = Observable.fromCallable(() -> {
    if (count.incrementAndGet() >= 3) {
        return new Bar();
    }
    throw new RuntimeException("bar exception");
});

when(barService.getBar()).thenReturn(o);

Upvotes: 2

Related Questions