2016-04-24 39 views
0

我想測試代碼的重試:重試在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

+0

調用'onError'或'onCompleted'帶來的'Subject's到終端狀態,沒有進一步的事件被接受/轉發。 – akarnokd

+0

瞭解。那麼正確的方法是什麼? – Blitzkr1eg

+0

如果你想用錯誤場景測試你的重試,你必須考慮你的代碼在哪種情況下可能導致onError並在你的測試中利用它。但正如他們告訴你的,調用onError或OnComplete將使主題完成。 – paul

回答

0

調用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);