Mocking Android HTTP responses

Adrian Coman
2 min readNov 16, 2020

A lot of times, the backend and frontend work aren’t perfectly synchronized.
As an Android engineer, you know that in the next sprint you should start implementing an API endpoint from the backend, but because of different constraints from the previous sprint, the API will not be ready.

What helped me overcome this limitation and not get blocked was deciding together with the backend engineer on a specific “contract” that we should follow regarding how the response will look like and then somehow mock that response.

In the example below I’m using OkHttp and Retrofit, but it can be easily accommodated for GraphQL.

This is how the objects from the response will look like. It’s an object that has an id, group_name, date_updated, and an icon.

Now, since we have the objects, let’s look at how the interceptor looks like:

Let’s dive into the code explanation:

Lines 4–7: we create our response as a string. We get each of the objects and create a string that looks like an array of objects.
Line 13: we’ll set the response code. In this case, we want it to be a success 200.
Line 15: we set the actual response body that we want to receive.
Line 16: we can add a header if it’s needed.

Another thing that’s useful is adding a condition to intercept only certain requests. For example, we want the “create group” request to reach the backend, but the “get group list” request to be intercepted and mocked. This is what I’ve done on line 11 (filter the request) and 19 (allow the initial request through).

Now that the whole setup is done, the only thing left is to add it to our OkHttpClient before building it, like this:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Adrian Coman
Adrian Coman

Written by Adrian Coman

Engineering Manager | ex-Android Developer

No responses yet

Write a response