如何对retrofit2回调进行单元测试?

时间:2016-05-16 16:15:13

标签: android unit-testing mockito powermock retrofit2

我想进行单元测试,以验证是否调用了function1()function2()。我之前没有使用回调,你能告诉我怎么做吗?

public void sendData(HttpService service, Document userData) {
    Call<String> call = service.updateDocument(getId(), userData);

    call.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        function1(response.code());
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        function2();
    }
    });
}

1 个答案:

答案 0 :(得分:0)

我无法尝试,但它应该有效。也许你必须修复泛型类型 抛出mock(Call.class);等错误。

@Test
public void should_test_on_response(){
    Call<String> onResponseCall = mock(Call.class);

    doAnswer(invocation -> {
        Response response = null;
        invocation.getArgumentAt(0, Callback.class).onResponse(onResponseCall, response);
        return null;
    }).when(onResponseCall).enqueue(any(Callback.class));

    sendData(....);

    // verify function1
}

@Test
public void should_test_on_failure(){
    Call<String> onResponseCall = mock(Call.class);

    doAnswer(invocation -> {
        Exception ex = new RuntimeException();
        invocation.getArgumentAt(0, Callback.class).onFailure(onResponseCall, ex);
        return null;
    }).when(onResponseCall).enqueue(any(Callback.class));

    sendData(....);

    // verify function2
}