我使用Retrofit
与RxJava
一起从网络中获取一些数据,将其映射到viewmodel对象并调用视图以显示数据。
这是我的代码的外观:
@Override
public void onLoadData() {
view.showProgressBar();
service.fetchCVRF(createRequestBody())
.map(this::mapToViewModels)
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.mainThread())
.subscribe(viewModels -> {
if (view != null) {
view.hideProgressBar();
view.showData(viewModels);
}
}, throwable -> {
if (view != null) {
view.hideProgressBar();
}
Timber.i(throwable, "onLoadData ");
});
}
我想用Mockito
对上面的代码进行单元测试,所以我做的是:
@RunWith(MockitoJUnitRunner.class)
public class CvrfPresenterTest {
@Mock private CvrfMVP.View view;
@Mock private CvrfService service;
@Mock private SharedPreferencesManager prefManager;
private BaseSchedulerProvider schedulerProvider;
private CvrfPresenter presenter;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
schedulerProvider = new ImmediateSchedulerProvider();
presenter = new CvrfPresenter(view, service, prefManager, schedulerProvider);
}
@Test
public void onLoadData() throws Exception {
// Given
when(service.fetchCVRF(any(RequestBody.class)))
.thenReturn(Single.just(response()));
when(service.fetchCVRF(any(RequestBody.class)).map(any()))
.thenReturn(Single.just(viewModels()));
// When
presenter.onLoadData();
// Then
verify(view).showData(anyList());
}
private Response<CvrfResponse> response() {
return Response.success(new CvrfResponse());
}
private List<CvrfViewModel> viewModels() {
return Collections.emptyList();
}
}
上述代码的问题在于,当我运行它时会为第二个NullPointerException
抛出when
。这不是我应该如何对这段代码进行单元测试吗?我认为我的代码很好,但我不明白为什么在调用NPE
运算符时它会给map
,因为我已经在第一个when
中定义了它应返回的内容。