Member-only story
Android Unit Testing With MockWebServer and Truth Assertion Library
Build bug-free Android apps

Testing is an important part of the software lifecycle. We developers tend to make mistakes. Testing ensures that our code behaves as expected. It also helps to find bugs early, maintain code standards, and save time.
First, we will know a little about MockWebServer
and the truth Assertion Library.
MockWebServer
According to the official documentation:
This library makes it easy to test that your app Does The Right Thing when it makes HTTP and HTTPS calls. It lets you specify which responses to return and then verify that requests were made as expected.
If you want to more please check here.
Truth
According to the official documentation:
Truth is a library for performing assertions in tests. Truth is owned and maintained by the Guava team. It is used in the majority of the tests in Google’s own codebase.
If you want to know more please check here.
Show me what we are Testing.

It is a great app. Isn’t it?
We will use this GitHub repository in this article. Feel free to check it.
TL;DR
- Add dependency of MockWebServer, Truth, and OKHTTP in build.gradle
- If plus(+) sign exist in JUNIT dependency remove it and add a proper dependency
- Create
ImageResponse.json
file insideapp/src/main/resources
folder - Create
ImageApiServiceTest
class underapp/test
- Set up the
MockWebServer
and write test
Let’s Test
First add the dependency Add dependency of MockWebServer, Truth, and OKHTTP in build.gradle. Please add the latest Version.