单元测试RxJava代码

时间:2018-03-27 11:27:13

标签: java mockito rx-java2

我使用RetrofitRxJava一起从网络中获取一些数据,将其映射到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中定义了它应返回的内容。

0 个答案:

没有答案