我試圖調試RxJava訂閱對象的內部成功回調,並驗證使用正確參數調用的那些內部某些方法。我讀了一些關於Captors的文章,雖然也許這是要走的路,但無法找到符合我需求的例子。Android - 如何在RxJava訂閱中調試回調
我與單元測試:的Mockito和JUnit的
// OrderHistoryPresenterImpl presenter;
public void loadOrderHistory(final int offset, final int limit) {
mCompositeSubscription.add(useCase.getOrderHistory(offset, limit)
.doOnError(throwable -> Timber.e(throwable, "Error"))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ListOfOrders>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {}
@Override
public void onNext(ListOfOrders listOfOrders) {
//
// I would like to verify the calls in this method
//
user.setTryoutCountActive(listOfOrders.getActiveTryoutsCount());
getView().addOrdersToView(listOfOrders);
mCompositeSubscription.clear();
}
})
);
}
這裏是我試圖用
@RunWith(MockitoJUnitRunner.class)
public class OrderHistoryPresenterTest {
// Boiler plate Dagger 2 setup + variable declarations
private ListOfOrders response;
private ListOfOrders spyListOfOrders;
private OrderHistoryPresenterImpl presenter;
@Mock private OrderHistoryUseCaseImpl useCase;
@Before
public void setUp() throws FileNotFoundException {
// Setup + dagger 2 setup…
response = Utils.fromJson(gson, this, "OrderHistory.json", type);
spyListOfOrders = spy(response);
presenter = new OrderHistoryPresenterImpl(app, useCase, user);
when(useCase.getOrderHistory(MOCK_USER_ACCESS_TOKEN)).thenReturn(Observable.just(spyListOfOrders));
}
@After
public void tearDown() {…}
@Test
public void shouldGetOrderAndCall_addOrdersToView_OnActivity() {
presenter.loadOrderHistory(MOCK_OFFSET, MOCK_LIMIT);
// works…
verify(useCase, times(1)).getOrderHistory(MOCK_USER_ACCESS_TOKEN);
// This fails because it gets called right away because it's async - what to do?
verify(view, times(1)).addOrdersToView(spyListOfOrders);
}
}
因此,大家可以看到,以測試它的測試我不知道如何測試內部的Subscriber<ListOfOrders>
回調方法。任何幫助將不勝感激!
所以如果你想測試你的「Observable」是否有效,你可以使用TestSubscriber並在它上面做斷言。參考:http://reactivex.io/RxJava/javadoc/rx/observers/TestSubscriber.html。但是,如果你想測試像onNext這樣的Subscriber方法,然後用'loadOrderHistory'傳遞這個人(而不是創建一個新的),這樣你就可以在你的測試中進行模擬。 –
簽出[RxJavaDebug](https://github.com/ReactiveX/RxJavaDebug)。它可能有幫助。 –