我正在尝试调试RxJava Subscription对象的内部成功回调,并验证其中的某些方法是否使用正确的参数进行调用。我读了一些关于Captors的内容,虽然这可能是要走的路,但却无法找到符合我需求的例子。
我正在进行单元测试: 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>
回调方法。任何帮助将不胜感激!
答案 0 :(得分:1)
如果你像这样重写你的方法,那就说吧,
// 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) {
load(listOfOrders)
}
})
);
}
void loadOrders(ListOfOrders list) {
// I would like to verify the calls in this method
user.setTryoutCountActive(listOfOrders.getActiveTryoutsCount());
getView().addOrdersToView(listOfOrders);
mCompositeSubscription.clear();
}
现在分别测试这个loadOrders
方法。因为它所关心的只是获取要处理的订单列表。它可以来自任何地方(不仅是可观察的)。
您现在可以对此方法进行单元测试。
如果要测试Observable,请使用TestSubscriber
查看您是否实际从Observable获取订单列表。
参考:https://reactivex.io/RxJava/javadoc/rx/observers/TestSubscriber.html