Hash
Hash

Reputation: 33

How can I do unit testing for retrofit callbacks?

I'm trying to create unitest case for retrofit 2 callbacks in android. I use for test mockito, MockWebServer and MockResponse.

public class LoginFragment extends Fragment {
/**
     * Actualiza el numero telefonico para el usuario
     *
     * @param phoneNumber
     */
    public  void phoneNumber(String phoneNumber) {
        HttpService service = Service.createService(HttpService.class, TOKEN);
        Call<Void> call = service.phonumber(phoneNumber, new User("", ""));
        call.enqueue(callback());
    }

    /**
     * @return Callback<Void>
     */
    public Callback<Void> callback() {
        return new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    dummy();
                } else {
                    Log.e(TAG, "problema");
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, " " + t);
            }
        };
    }

    public void dummy(){
        System.out.println(" called");
    }
}

My unitest class:

@RunWith(MockitoJUnitRunner.class)
public class TestLoginFragment {
   MockWebServer mockWebServer;

    @Before
    public void setup() throws Exception {
        spyLoginFragment = mock(LoginFragment.class);
        mockWebServer = new MockWebServer();
    }


    @Test
    public void testDummyIsCalled() {
        spyLoginFragment.phoneNumber("3333335");
        mockWebServer.enqueue(new MockResponse().setResponseCode(201));
        verify(spyLoginFragment, times(1)).dummy();
    }
}

But when you run the test I get:

TestLoginFragment > testDummyIsCalled FAILED
    Wanted but not invoked:
    loginFragment.dummy();

I'm new making callback test, how can I verify that dummy() was called?

Upvotes: 2

Views: 2581

Answers (1)

Viktor Valencia
Viktor Valencia

Reputation: 435

By definition, unit test only tests the functionality of the units themselves. Therefore, it may not catch integration errors.

You shouldn´t test the retrofit framework or its callbacks, you must be presumed that retrofit always works. Only Test your code, so create a test for phoneNumber(String phoneNumber) that checks if the service was configured correctly (not need to launch retrofit service), and create others test to check the posible responses from the server in OnSuccess or OnFailure cases.

PD: If you want to test the coupling between the Retrofit call and the callback's methods, then you're talking about "integration test".

Upvotes: 0

Related Questions