Effectively Mock the API in Android

Atul Sakhala
2 min readAug 3, 2022

Lighting fast API integration.

Why do we need to mock the API responses?

  • It fastens and backend independent API integration
  • Easily follows the TDD approach
  • Validate the backend API responses.
  • Increase the code coverage, and test end-to-end flow because no wait or delay is required to test the async callback.

How we can achieve this?

So In android development what are the first and last things that interact with API requests and responses? The simple answer is Interceptor,

So we can build an interceptor that would validate each APIs call and instead of actually firing on the server it goes to mock and return the dummy responses.

Let’s try then

class MockRequestInterceptor : Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
.........
}}

So I created a MockRequestInterceptor which extends the Interceptor interface and has a method entry and exit gate for each API call so that we have at least one place for playing with requests and responses.

Before that Now I’ll create an Enum class to segregate all the types of responses either success or failure.

enum class MockCallType {
VALID_RESPONSE,
INVALID_RESPONSE
}

Now my interceptor is ready for plug n play. Also, we can write some unit tests around to validate this, meanwhile, backend guys are working on creating the APIs.

A simple and useful way to one step closer to a multi-module approach.

Hit Clap if you like the content, also you need any help around then comment down below or drop me a message and email on LinkedIn

Follow my BaseRepo project for smooth integration learning.

Thanks, This is the way !!

--

--

Atul Sakhala

Android Developer with the fusion of Scientific Spirituality - FreeLancer, Founder of GameReel.gg and Tryhard.gg, Ex-Rivigo, Ex-BharatPe