Retrofit 2 – Mocking HTTP Responses

In the previous post, I discussed implementing a custom Retrofit Client to mock out different HTTP response codes. This mechanism works well for Retrofit versions 1.9 and below but has its drawbacks. After trying out Retrofit 2, I have adjusted the previous sample and managed to achieve the same results (with some improvements 😀).

In order to test your android apps, one thing that normally gets frequently overlooked is the apps ability to handle different server responses. What if your server goes down for a while? Does your app fall over with it – or does it gracefully recover? Things like this are difficult to emulate with real servers, which is why mocking responses is such a great way to ensure your app is awesome.

In this example, we will look at creating an app that retrieves a quote of the day from a web service and displays it to the user. We will also add a failure mechanism to the front end to show the user a retry button if something goes wrong. We will also look at testing these failure mechanisms.

Example 1:

  1. Create a Rest Service interface that will be used with Retrofit.
  2. Ensure your activity calls the Retrofit Service that you have just created. In the code below, the service gets created and the activity asynchronously calls getQuoteOfTheDay() . When a successful response is received from the server, the quote is displayed otherwise a retry button is shown with an error message.
  3. You might wonder, how do we test that the retry button is properly shown when the server is down without turning the server off? 😁 Using Espresso and Retrofit MockWebServer we can easily achieve this. Create mock JSON and store it in your androidTest  folder.
    Success Response Sample JSON:

    404 Not Found Sample JSON:
  4. Below is the sample for testing the positive case (a quote is displayed to the user) and the negative case. A retry button is displayed to the user when the server is returning an error. You might want to do some other logic when there is an error but for simplicity we will just display a retry button.

    From the sample above, we can see that the method setUp() is starting up the MockWebServer and setting the BASE_URL  of the entire app to point to the local mock server’s url.
    The test testQuoteIsShown()  is enqueuing a 200 OK response on the mock server, with the JSON from the file we defined previously as the body. We then launch the Activity. Using Espresso, we ensure that the retry button is hidden and the quote is displayed.
    The test testRetryButtonShowsWhenError() does a similar thing, except it queues up a 404 response, ensures that the retry button is shown and that the text “Quote Not Found” is displayed.
  5. As you can see from the above sample, we have achieved the same results as the previous post, but using Retrofit 2.

Pros of testing this way:

  • Really simple to test different HTTP Status Codes
  • Not much code needed to emulate the different responses

Cons of testing this way:

  • Difficult to dynamically create the responses

Example 2:

In the sample app, I have also included another way to test your Rest API by implementing the interface defined at the very beginning.

  1. Create a mock implementation of your API methods. In this stub, we create a dummy quote and return that quote every time. This is defined in the androidTest folder.

    2. Create another mock implementation that will return the error scenario.

3. Create a test which will test the API response parsing.

As you can see, the implementation that we mocked out previously is now being used in the test. In the  setUp()  method the MockRetrofit object is created. This MockRetrofit object wraps around the dummy implementation that we created and emulates a network call by adding delays onto the calls.

The testRandomQuoteRetrieval()  uses the first mock implementation to test the positive scenarios, whereas  testFailedQuoteRetrieval()  uses the second mock implementation which will return a 404 error.

This can be used to test operations on the API and test front end scenarios such as adding items to the server without sending it off to the server unnecessarily.

Pros of testing this way:

  • Can create rich data to return to the tests which means testing can be more meaningful
  • Easy enough to set up
  • JSON isn’t static


  • Have to create new API implementations for different error scenarios
  • Hard to see from a glance what the API returns

I think a combination of the two mechanisms described above can definitely cover most scenarios that you would need to test in order to make your app stable. What are your thoughts?

You can check out the full project here on Github.

If you enjoyed this blog post – please consider buying me a cupcake!

No. of Cupcakes

24 Replies to “Retrofit 2 – Mocking HTTP Responses”

  1. Excellent post! Id like to ask you one quick question about retrofit2: Have you managed to print your raw JSON responses from server in the positive case? I read that it’s possible with retrofit2 but can’t figure out how. The article was really useful and pleasant to read. Thanks.

  2. Hi!
    Thanks for the feedback.
    Yes I actually had the same thoughts whilst working through this example. It is possible, I have also included some basic logging in my example app on Github. You can find the code here:
    Obviously you might want to do a bit more logging.

    There are more examples of this online, for example the StackOverflow question:

  3. Hi!
    Thanks for the feedback.
    Yes I actually had the same thoughts whilst working through this example. It is possible, I have also included some basic logging in my example app on Github. You can find the code here:
    Obviously you might want to do a bit more logging.

    There are more examples of this online, for example the StackOverflow question:

  4. Wonderful the quote about the maintenance guy 😀 , and very interesting post ! Thank you a lot 🙂

  5. Hi, this is a great writeup on Retrofit2. I am curious though, why your getQuoteOfTheDay() method calls showRetry() twice. Wouldn’t it be better to handle the error in one fell swoop, and call showRetry() once (with the right message)?

  6. Hi Rebecca, do you know if retrofit2 support oauth2? or what is the best way to authenticate with oauth2?

  7. hi Rebecca, thanks, and nice blog, i’m going to check out your link and I’ll tell you how it was

  8. Good job Rebecca… I really liked this post. On the side note. Have you noticed that in recent beta version(beta4) they have changed the interfaces? Can you please update your post to include the updated beta version?

  9. Great article…. after hunting for so many article found this cool post.
    Thanks a lot 🙂

  10. Thank you for the post. I have a question. When does the server.enqueue() get called? For example, I want to mock an api response after clicking a “Login” button which calls /api/login endpoint.

  11. You need to call server.enqueue() – as you will be enqueuing the information yourself to the mock web server, so the information needs to be available on the mocked server before the API call gets executed.

  12. Hi Rebecca,
    I like the tutorial very much. However when I try applying this solution to my project I keep getting “Test running failed: Unable to find instrumentation info for: ComponentInfoTest running failed: Unable to find instrumentation info for: ComponentInfo{com.example.flavour1.demo.debug.test/}. I have the runner in defaultConfig section and have it selected in run configuration as well. Can you provide some pointers as to what to try next ? I’m really stuck reading almost 2 days with no success.

    Thanks in advance,

  13. Hi Kalin,
    Have you included the android test runner dependency in your build.gradle file?
    Make sure this is in your app level build.gradle:
    androidTestCompile (“”)

    Also, have you tried running the task using gradle by itself? So from command line (in your projects folder) try run ./gradlew connectedAndroidTest to see if it is maybe just an Android Studio configuration.

  14. Do you know if it should also work with rx.Observable and rx.Subscriptions? I tried, but could not get it to work.

    Observable authenticate(
    @Query(“username”) String username,
    @Query(“password”) String password,
    @Query(“grant_type”) String grantType,
    @Query(“scope”) String scope);

    server.enqueue(new MockResponse()

  15. Hey! first of all, awesome post!
    I was wondering how would I set my own custom error message for a failed response
    You sent a Json on the following call, but I’m not sure how retrofit extracts the error from it?

    Response errorResponse = Response.error(404, ResponseBody.create(MediaType.parse(“application/json”), “Error?”));

  16. Nevermind, figured it out: It’s a bit convoluted but it works 🙂
    Let me know if you know a btter way though

    okhttp3.Response response = new okhttp3.Response.Builder()
    .request(new Request.Builder().url(“http://localhost/”).build())

    Response<ArrayList> errorResponse = Response.error(ResponseBody.create(MediaType.parse(“application/json”), “”), response);

Leave a Reply