繁体   English   中英

在rxJava中重试

[英]Retry in rxJava

我想在代码中测试重试:

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

调用onErroronCompleted会使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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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