Distrito Telefónica. Innovation & Talent Hub
Initial Usage Example
employees.json
[
{
"id": "id_01",
"name": "Paul",
"surname": "Smith",
"age": 25,
"position": "Engineer"
},
{
... // More employees
}
]
Now, all that remains is to enqueue the responses for each specific path request, defining the precise response we intend to receive.
class EnqueueMockResponses @Inject constructor(
private val mockHelper: MockHelper
) {
fun enqueueEmployeeList() {
mockHelper.enqueue {
whenever(
path = "/our_endpoint_route/employees",
method = Method.Get
).thenReturnFromFile(
pathFromFile = "employees.json",
httpResponseCode = 200,
delayInMillis = 2000L
)
}
}
}
Let’s explore the internal workings of the library.
First Step: Setup the library
fun setUp(
port: Int = 0,
enableSsl: Boolean = false,
) {
mockApiClient.setUp(enableSsl = enableSsl)
mockApiClient.startServer(port)
}
In instances where the port is left unspecified, the server dynamically selects an available port during initialization. Once the server is initialized, configuring our HTTP client becomes straightforward. A crucial step involves informing the client of the base URL for our requests, which is obtained from the newly launched server.
suspend fun getBaseUrl(): String = mockApiClient.getBaseUrl()
Second Step: Provide mock responses
fun enqueue(block: EnqueuingContext.() -> Unit) = block(EnqueuingContext(this))class EnqueuingContext(val mockHelper: MockHelper) {
fun whenever(
path: Path,
method: Method = Method.Get
): MockResponseBuilderWithRequestInfo = MockResponseBuilderWithRequestInfo(mockHelper, RequestInfo(path, method))
}class MockResponseBuilderWithRequestInfo(
private val mockHelper: MockHelper,
private val requestInfo: RequestInfo,
) {
fun thenReturnFromFile(
pathFromFile: String,
httpResponseCode: Int = MockedResponse.DEFAULT_MOCK_HTTP_RESPONSE_CODE,
delayInMillis: Long = MockedResponse.DEFAULT_MOCK_DELAY_IN_MILLIS,
) {
mockHelper.mockApiClient.enqueue(
requestInfo = requestInfo,
mockedResponse = MockedApiResponse(
body = mockHelper.fileReader.readJsonFile(pathFromFile) ?: MockedApiResponse.DEFAULT_BODY,
httpResponseCode = httpResponseCode,
delayInMillis = delayInMillis,
)
)
}
}
The matching of specified paths is done using Regex; this way, we enable the mocking of requests with dynamic values.
fun enqueueEmployeeList() {
mockHelper.enqueue {
whenever(
path = "api/.*/our_endpoint_route?employee_id=.*",
method = Method.Get
).thenReturnFromFile(
pathFromFile = "employee_detail.json",
httpResponseCode = 200,
delayInMillis = 2000L
)
}
}
Previous mock match with next example urls:
https://localhost:8080//api/1.0.0/our_endpoint_route?employee_id=001
https://localhost:8080//api/1.0.1/our_endpoint_route?employee_id=002
Third Step: Create JSON responses
Our Android Mock Api Server Library