我试图调试RxJava订阅对象的内部成功回调,并验证内部使用正确参数调用的某些方法。我读了一些关于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>
回调方法。任何帮助将非常感激!
假设你像这样重写你的方法,
// 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