6

I want to do an unit test that verifies if function1() or function2() were called. I haven't work with callbacks before, can you give me any idea about how to do it?

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();
    }
    });
}
kris larson
  • 30,387
  • 5
  • 62
  • 74
Jimmy A. León
  • 541
  • 3
  • 6
  • 22

1 Answers1

1

I couldn't try, but it should work. Maybe you have to fix generic type casting errors like 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
}
utkusonmez
  • 1,486
  • 15
  • 22