Retrofit 2 mock best practice

I usually use Mockito like this

  1. Import Retrofit Mock

    <dependency>
        <groupId>com.squareup.retrofit2</groupId>
        <artifactId>retrofit-mock</artifactId>
        <version>${version.retrofit}</version>
        <scope>test</scope>
    </dependency>
    
  2. Create and use the mock

    import retrofit2.mock.Calls;
    import static org.mockito.Mockito.when;
    import static org.mockito.Mockito.mock;
    
    ...
    
    Api api = mock(Api.class); // Mockito mock
    
    ...
    
    when(api.doSomething(param)).thenReturn(Calls.response(response));
    

Retrofit Mock is used only to generate the response.


This issue on Retrofit's Github repo is asking about the non-existent documentation you were asking about (it is still open while writing this answer).

Well, you have 2 options (both are in the article you already mentioned), and it depends on how you want to define your Givens/Inputs:

Option 1: (Okhttp's MockWebServer)

If you usually start your TDD by dealing with your backend's json response (using something like Postman), & you would feel more confident if you used that returned json directly as the input for your tests, then use MockWebServer, where you would copy/paste the json you already have & start developing your tests from there.

Option 2: (Retrofit's own Mock Web Server)

If you prefer defining your givens/inputs using objects for the models you already use in your code, which would make your tests more readable & controllable, then use Retrofit's mock web server just like how it is used in this official sample mentioned by @JakeWharton


Both options are developed/maintained by the same awesome people of Square, so it is really about how you want to define your givens/inputs.