Given the following SomePresenter/ SomeViewModel.java
void someAction(){
subscription = someObservable()
.subscribeOn(getBgThread())
.compose(screenProgressDialog.bindLoading())
.observeOn(getUiThread())
.subscribe(new Subscriber<GetDailyHistoryEvent>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Timber.e(e);
screenToast.show(R.string.error_generic_server_message, Toast.LENGTH_SHORT);
}
@Override
public void onNext(GetDailyHistoryEvent someObject) {
updateUI(someObject);
}
});
}
Then the test:
@Before
public void setup() {
Mockito.doReturn(testScheduler).when(viewModel).getBgThread();
Mockito.doReturn(Schedulers.immediate()).when(viewModel).getUiThread();
Mockito.doReturn(RxTestUtils.newDummyComposeTransformer())
.when(screenProgressDialog)
.bindLoading();
}
@Test
public void test_fetchBookingDetails_woCache() {
BookingDetail bookingDetail = BookingDetail.builder()
.forTest()
.build();
GetDailyHistoryEvent.DailyHistory dailyHistory = GetDailyHistoryEvent.DailyHistory.create("dafwe", null, Collections
.singletonList(bookingDetail), 1, true);
GetDailyHistoryEvent getDailyHistoryEvent = GetDailyHistoryEvent.create(Collections.singletonList(dailyHistory));
viewModel.timeCreated = bookingDetail.getCreatedTime();
viewModel.cachedData.clear();// force fetch from remote
Mockito.doReturn(Observable.just(getDailyHistoryEvent))
.when(historyRepository)
.sendGetDailyHistory(Mockito.anyString());
Mockito.doNothing()
.when(viewModel)
.updateUI(getDailyHistoryEvent);
viewModel.fetchBookingDetails();
testScheduler.triggerActions();
Mockito.verify(viewModel)
.updateUI(getDailyHistoryEvent);
}
@Test
public void test_fetchBookingDetails_woCache_Error() {
viewModel.timeCreated = "faef;aewfoiawefoia";
viewModel.cachedData.clear();// force fetch from remote
Mockito.doReturn(Observable.error(new Exception("something wrong")))
.when(historyRepository)
.sendGetDailyHistory(Mockito.anyString());
viewModel.fetchBookingDetails();
testScheduler.triggerActions();
Mockito.verify(viewModel, Mockito.never())
.updateUI(Mockito.any(GetDailyHistoryEvent.class));
Mockito.verify(screenToast).show(Mockito.anyInt(), Mockito.anyInt());
}