Blog Infos
Author
Published
Topics
Published

mockresponseinterceptor

 

In Android development, testing API integrations can be challenging, especially when you need to simulate different server responses. This is where MockResponseInterceptor comes to the rescue. MockResponseInterceptor is an open-source library that simplifies the process of mocking Retrofit API responses in Android applications. In this article, we will explore how to use MockResponseInterceptor to streamline API response mocking in your Android projects.

What is MockResponseInterceptor?

MockResponseInterceptor is a powerful library that allows you to fetch data from local JSON files without making any changes to your existing Retrofit endpoints. With MockResponseInterceptor, you can seamlessly switch between real server responses and mocked responses during development and testing. It provides a simple yet effective way to simulate different scenarios and ensure your app behaves correctly under various conditions.

Easy-to-use Annotation-based Approach

MockResponseInterceptor offers an annotation-based approach to mock Retrofit API responses. By simply annotating your Retrofit API methods with the @Mock annotation, you can define the mock JSON file for each endpoint.

Local Testing of Your App with Mock Responses

With MockResponseInterceptor, you can test your Android app locally using mock responses from local JSON files. This eliminates the need to rely on a server for testing, allowing you to iterate quickly and efficiently.

Dynamic Global Mocking Configuration

MockResponseInterceptor provides dynamic configuration change support, enabling you to change the global mocking behavior on the fly. This is especially useful when you want to simulate different scenarios without recompiling your app or modifying the code.

Customizable Filename Extraction

You can customize the filename extraction strategy for the mock JSON files. This allows you to define your naming conventions based on the URL or any other criteria that suit your project requirements.

Getting Started with MockResponseInterceptor

Now let’s dive into the steps required to integrate MockResponseInterceptor into your Android project.

Step 1: Add the Dependency

To get started, add the MockResponseInterceptor dependency to your project. Open your module’s build.gradle file and add the following dependencykotlinCopy code

dependencies {
    implementation "com.github.mustafayigitt:MockResponseInterceptor:1.0.0"
    // Other dependencies
}
Step 2: Initialize MockResponseInterceptor

Next, you need to initialize MockResponseInterceptor in your application code. You can do this by creating an instance MockResponseInterceptor.Builder and configuring it according to your needs. Here’s an example of how to initialize MockResponseInterceptor:

MockResponseInterceptor.Builder(context.assets).build()
// or
MockResponseInterceptor.Builder(context.assets)
    .isGlobalMockingEnabled { MainActivity.isGlobalMockingEnabled }
    .fileNameExtractor { url -> "yourNamingStrategy" }
    .build()

In the above code, we first create an instance MockResponseInterceptor.Builder by passing the context.assets object. This provides access to the local assets folder where we store the mock JSON files. Then, we can optionally configure the global mocking behavior and customize the filename extraction strategy using the builder’s methods. Finally, we call the build() method to obtain the MockResponseInterceptor instance.

Step 3: Annotate Retrofit API Methods

To enable mocking for specific Retrofit API methods, you need to annotate them with the @Mock annotation. Here’s an example:

@GET("top-headlines")
@Mock
suspend fun getNews(
    @Query("language") country: String = "en",
    @Query("apiKey") apiKey: String = BuildConfig.NEWS_API_KEY,
): Response<NewsWrapperModel>

 

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

No results found.

In the above code, we annotate the getNews() method with @Mock to indicate that we want to mock its response. MockResponseInterceptor will look for a corresponding mock JSON file based on the endpoint URL in the assets folder.

Step 4: Create Mock JSON Files

To create a mock JSON file for a specific API endpoint, you need to follow a naming convention. By default, MockResponseInterceptor uses the endpoint URL to derive the mock JSON file name. For example, if your endpoint URL is, the mock JSON file should be named top-headlines.json. The content of the mock JSON file should match the response structure expected by your app.

Here’s an example of a mock JSON file for the "top-headlines" endpoint:

{
  "articles": [
    {
      "title": "MockResponseInterceptor - Mock your Retrofit API responses",
      "urlToImage": "https://picsum.photos/200"
    }
  ]
}

In the above JSON, we define a single article with a title and an image URL. This mock JSON file will be used as the response when the getNews() method is invoked during testing or development.

Step 5: Run and Test Your App

With MockResponseInterceptor integrated into your project, you can now run and test your app locally. The Retrofit API methods annotated @Mock will return the mock responses defined in the corresponding JSON files. This allows you to simulate different scenarios, test edge cases, and verify the behavior of your app without relying on a real server.

How It Works

MockResponseInterceptor consists of two key classes: MockResponseInterceptor and MockResponseManager. Let’s explore how these classes work together to provide seamless Retrofit API response mocking.

MockResponseInterceptor

The MockResponseInterceptor class implements the Interceptor interface from OkHttp. It intercepts the requests made by Retrofit and handles the mocking logic. Here’s an overview of its main functionalities:

Intercepting Requests: The intercept method intercepts the requests made by Retrofit. It first checks if the global mocking is enabled. If not, it proceeds with the original request by calling chain.proceed(initialRequest). If mocking is enabled, it checks if the current request is annotated with @Mock. If it is, the method proceeds to retrieve the mock response; otherwise, it proceeds with the original request.

Retrieving Mock Response: The getMockResponse method is responsible for retrieving the mock response based on the request. It uses the MockResponseManager to obtain the JSON string for the mock response. It then creates an OkHttp Response object with the mock response data and returns it.

MockResponseManager

The MockResponseManager class handles the retrieval of the mock response JSON from the local assets folder. Here’s an overview of its main functionalities:

Getting JSON by URL: The getJsonByUrl method retrieves the mock response JSON based on the provided request. It first extracts the file name from the request using the getFileNameFromRequest method. It then opens the corresponding JSON file from the assets folder and reads its content as a string.

File Name Extraction: The getFileNameFromRequest method extracts the file name from the request by examining the annotations on the request method. It supports various HTTP methods such as GET, POST, PUT, DELETE, and PATCH. If a custom file name extraction strategy is provided, it is used to determine the file name. Otherwise, it converts the request URL path into a suitable JSON file name.

JSON File Name Conversion: The convertToJsonFileName method converts the request URL path into a valid JSON file name. It replaces slashes, query parameters, and special characters with underscores. It also ensures that consecutive underscores are replaced with a single underscore and removes trailing underscores. The resulting string is then converted to lowercase.

By combining the functionalities of MockResponseInterceptor and MockResponseManager, MockResponseInterceptor simplifies Retrofit API response mocking in Android applications, making it easier to test and develop apps that rely on API integrations.

Conclusion

MockResponseInterceptor simplifies the process of mocking Retrofit API responses in Android applications. By leveraging local JSON files, you can easily test your app’s behavior under different scenarios without relying on a server. With its annotation-based approach and dynamic configuration support, MockResponseInterceptor streamlines the process of API response mocking during development and testing.

To learn more about MockResponseInterceptor and get started with it, check out the GitHub repository. Happy mocking!

This article was previously published on proandroiddev.com

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
This is the second article in an article series that will discuss the dependency…
READ MORE
blog
Let’s suppose that for some reason we are interested in doing some tests with…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu