我想在代码中测试重试:
public Observable<Foo> getFoo() {
return barService.getBar()
.retry(3)
.map(barToFoo);
}
和单元测试:
//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());
以java.lang.AssertionError: Unexpected onError events: 1
答案 0 :(得分:1)
调用onError
或onCompleted
会使Subject
进入终端状态,并且不会接受/转发其他事件。
通常情况下,您无法使用Subject
重试,但可以尝试使用fromCallable
和计数器:
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);