PROFESSIONAL ANDROID
APP DEVELOPMENT
MOCKWEBSERVER
MOOCWEBSERVER 1
Android
MockWebServer
At the course, we have been talking about unit tests and the importance of them.
As a developers we will face several challenges when writing the like isolating the
tests, mocking dependencies, testing UI, testing the networks calls, and others.
This time, we want to talk about a library that will help us when we need to write
unit tests for our network calls: MockWebServer. It helps us to make the tests that
our app is doing the right thing when it makes http(s) requests.
With mockWebServer we can specify which responses to return when we call
and endpoint and with that information we can verify that the request was as
expected and that the code is behaving correctly.
You can also do tests like verify if your code survives in situations like 500 errors
or slow-loading responses.
To start using mockWebServer on your unit tests for your Android app you can
import the project dependency using Gradle:
testCompile '[Link].okhttp3:mockwebserver:(insert latest
version)'
You can mock responses, and even set the header values that you want to verify
on your api calls:
MockResponse response = new MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Cache-Control", "no-cache")
.setBody("{}");
The MockResponse object can also be used to simulate a slow network using the
throttleBody method:
[Link](1024, 1, [Link]);
You can also make a lot of more type of tests over the interaction between a
server and your application. You can user the object RecorderResquest to assert
that you are sending correctly the headers or body parameters on it.
If you want to get more deep on how to use mockWebServer we recommend that
you read their documentation on its Github repository:
[Link]