Throughout Android improvement, API integration testing may be difficult, particularly when you want to simulate totally different server responses. That is the place the MockResponseInterceptor involves the rescue. MockResponseInterceptor is an open supply library that simplifies the simulation of Retrofit API responses in Android purposes. On this article, we are going to discover the best way to use MockResponseInterceptor to simplify API response simulation in your Android tasks.
MockResponseInterceptor is a robust library that permits you to fetch information from native JSON recordsdata with out making any modifications to your present Retrofit endpoints. With the MockResponseInterceptor, you possibly can seamlessly change between the actual server response and the mock response throughout improvement and testing. It supplies a easy but efficient method to simulate totally different situations and guarantee your software works appropriately beneath totally different circumstances.
A simple-to-use annotation-based strategy
MockResponseInterceptor supplies an annotation-based strategy to simulate Retrofit API responses. Simply annotate your retrofit API strategies with @Mock
Notice, you possibly can outline a dummy JSON file for every endpoint.
Take a look at your app domestically with Faux Suggestions
With MockResponseInterceptor, you possibly can take a look at your Android app domestically utilizing mock responses from native JSON recordsdata. This eliminates the necessity to depend on the server for testing, permitting you to iterate rapidly and effectively.
Dynamic World Mocking Configuration
MockResponseInterceptor supplies help for dynamic configuration modifications, permitting you to rapidly change international mocking conduct. That is particularly helpful while you wish to simulate totally different situations with out recompiling your software or modifying the code.
Customizable filename extraction
You possibly can customise the filename extraction technique for dummy JSON recordsdata. This lets you outline your naming conference based mostly on URLs or another standards that match your undertaking necessities.
Now let’s dive into the steps required to combine MockResponseInterceptor into your Android undertaking.
Step 1: Add dependencies
To get began, add the MockResponseInterceptor dependency to your undertaking. Open your module construct.gradle
file and add the next dependency codekotlinCopy
dependencies {
implementation "com.github.mustafayigitt:MockResponseInterceptor:1.0.0"
// Different dependencies
}
Step 2: Initialize MockResponseInterceptor
Subsequent, you want to launch the MockResponseInterceptor in your software code. You are able to do this by creating an occasion MockResponseInterceptor.Builder
and configure it in response to your wants. Right here is an instance of the best way to initialize the MockResponseInterceptor:
MockResponseInterceptor.Builder(context.belongings).construct()
// or
MockResponseInterceptor.Builder(context.belongings)
.isGlobalMockingEnabled { MainActivity.isGlobalMockingEnabled }
.fileNameExtractor { url -> "yourNamingStrategy" }
.construct()
Within the above code, we first create an occasion MockResponseInterceptor.Builder
by the way in which go it context.belongings
Factor. This supplies entry to the native belongings listing the place we retailer the dummy JSON recordsdata. We are able to then optionally configure the worldwide mocking conduct and customise the filename extraction technique utilizing generator strategies. Lastly, we name the construct()
technique to get MockResponseInterceptor
For instance.
Step 3: Annotate retrofit API strategies
To allow mock mode for particular Retrofit API strategies, you want to annotate them with @Mock
be aware. Right here is an instance:
@GET("top-headlines")
@Mock
droop enjoyable getNews(
@Question("language") nation: String = "en",
@Question("apiKey") apiKey: String = BuildConfig.NEWS_API_KEY,
): Response
Within the above code, we annotate getNews()
technique with @Mock
to point that we wish to mock its response. The MockResponseInterceptor will search for the corresponding dummy JSON file based mostly on the endpoint URL within the belongings listing.
Step 4: Create dummy JSON recordsdata
To create a dummy JSON file for a particular API endpoint, you want to observe the naming conference. By default, the MockResponseInterceptor makes use of the endpoint URL to get the dummy JSON filename. For instance, in case your endpoint URL is, the dummy JSON file must be named top-headlines.json
. The content material of the dummy JSON file should match the response construction anticipated by your software.
Right here is an instance of a dummy JSON file for "top-headlines"
ultimate level:
{
"articles": [
{
"title": "MockResponseInterceptor - Mock your Retrofit API responses",
"urlToImage": "https://picsum.photos/200"
}
]
}
Within the JSON above, we outline an article with a title and a picture URL. This dummy JSON file will likely be used because the response when getNews()
technique is known as throughout testing or improvement.
Step 5: Run and take a look at your software
With the MockResponseInterceptor constructed into your undertaking, now you can run and take a look at your software domestically. Annotated retrofit API strategies @Mock
will return mock responses outlined within the respective JSON recordsdata. This lets you simulate totally different situations, take a look at edge instances, and confirm software conduct with out counting on an actual server.
MockResponseInterceptor consists of two primary courses: MockResponseInterceptor
And MockResponseManager
. Uncover how these layers work collectively to supply seamless Retrofit API response emulation.
MockResponseIntercept
The MockResponseInterceptor
the category implements the Interceptor
interface from OkHttp. It intercepts requests made by Retrofit and handles emulation logic. Right here is an summary of its primary capabilities:
block request: the intercept
intercept requests made by Retrofit. First, it checks if international emulation is enabled. In any other case, it continues with the unique request by calling chain.proceed(initialRequest)
. If emulation is enabled, it checks if the present request is annotated with @Mock
. If that’s the case, the strategy will proceed to retrieve the mock response; in any other case it continues with the unique request.
Retrieve faux responses: the getMockResponse
the strategy is liable for retrieving the mock response based mostly on the request. It makes use of MockResponseManager
to get the JSON string for the mock response. Then it creates an OkHttp Response
object with simulated response information and return it.
MockResponseManager
The MockResponseManager
class that handles retrieving the mock response JSON from the native belongings listing. Right here is an summary of its primary capabilities:
Get JSON by URL: the getJsonByUrl
technique that retrieves a mock response JSON based mostly on the supplied request. It first extracts the filename from the request utilizing getFileNameFromRequest
technique. It’s going to then open the corresponding JSON file from the belongings folder and browse its contents as a string.
Extract filename: the getFileNameFromRequest
the strategy extracts the filename from the request by checking the annotations on the request technique. It helps totally different HTTP strategies like GET, POST, PUT, DELETE and PATCH. If a customized filename extraction technique is supplied, it is going to be used to find out the filename. In any other case, it is going to convert the request URL path to an acceptable JSON filename.
Convert filename to JSON: the convertToJsonFileName
convert request URL path to legitimate JSON filename. It replaces slashes, question parameters, and particular characters with underscores. It additionally ensures that consecutive underscores are changed by a single underscore and removes trailing underscores. The ensuing string is then transformed to lowercase.
By combining the capabilities of MockResponseInterceptor
And MockResponseManager
MockResponseInterceptor simplifies Retrofit API response emulation in Android apps, making it simpler to check and develop apps based mostly on API integration.
MockResponseInterceptor simplifies the method of simulating Retrofit API responses in Android purposes. By leveraging native JSON recordsdata, you possibly can simply take a look at the conduct of your software in numerous situations with out counting on the server. With an annotation-based strategy and dynamic configuration help, MockResponseInterceptor streamlines the method of simulating API responses throughout improvement and testing.
To be taught extra about MockResponseInterceptor and get began with it, try the GitHub repository. Completely happy mocking!