在rxJava中重试

时间:2016-04-24 08:23:52

标签: java unit-testing rx-java reactive-programming

我想在代码中测试重试:

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

失败

1 个答案:

答案 0 :(得分: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);