android中的改装回调单元测试

时间:2018-10-15 16:23:00

标签: android unit-testing mocking mockito retrofit2

嗨,大家好,我是MVVM和单元测试的初级android开发人员。在我的代码中,我想编写测试,而在我的测试中,我想模拟我的改造回调。并检查我的模块行为,以获取服务器的多次响应以及200或401服务器代码等多个代码。 我该怎么办?

那是我的RequestCallback.java

private MediatorLiveData<ServerResponseStatus> responseStatus = new MediatorLiveData<>();
private RequestListener<T, V> listener;
private TypeToken<V> type;

{
    responseStatus.setValue(ServerResponseStatus.STARt);
}

public RequestCallback(Call<T> call, RequestListener<T, V> listener, TypeToken<V> type) {
    this.listener = listener;
    this.type = type;

    responseStatus.postValue(ServerResponseStatus.SHOW_LOADING);

    call.enqueue(this);

}


@Override
public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {

    responseStatus.postValue(ServerResponseStatus.HIDE_LOADING);

    if (response.code() >= 200 && response.code() < 300)
        listener.onResponse(response);
    else {
        if (response.code() == 401)
            responseStatus.postValue(ServerResponseStatus.UNAUTHORIZED);

        try {
                String errorResponse = response.errorBody().string();
                Gson gson = new Gson();
                V fromJson = gson.fromJson(errorResponse, type.getType());
                listener.onError(fromJson);
            } catch (Exception e) {
                e.printStackTrace();
                listener.onFailure(response.code(), response.message());
            }
    }

}

@Override
public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
    responseStatus.postValue(ServerResponseStatus.HIDE_LOADING);
    listener.onFailure(500, t.getMessage());
}


public MediatorLiveData<ServerResponseStatus> getResponseStatus() {
    return responseStatus;
}

这是我的测试

@Test
public void checkTimeTest(){

    ApiInterface mockedApiInterface = Mockito.mock(ApiInterface.class);
    Call<TimeCheckResponse> mockedCall = mock(Call.class);

    when(mockedApiInterface.timeCheck()).thenReturn(mockedCall);



    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {

            Callback<TimeCheckResponse> callback = invocation.getArgument(0);
            TimeCheckResponse timeCheckResponse = new TimeCheckResponse("IR");
            callback.onResponse(mockedCall, Response.success(timeCheckResponse));

            return null;
        }
    }).when(mockedCall).enqueue(any(Callback.class));





    timeChecker.check(timeCheckerListener);

    verify(timeCheckerListener).onCorrectTime();


}

这是我的答复

    Wanted but not invoked: timeCheckerListener.onCorrectTime();-> at com.teskaco.bbpos.splash.SplashScreenViewModelTest.checkTimeTest(SplashScreenViewModelTest.java:85)
Actually, there were zero interactions with this mock.

0 个答案:

没有答案