Unit Test Retrofit API calls with MockWebServer
In this article, we are going to test our ViewModel in our sample Android app which contains the logic for requesting employee details using Retrofit. We have the following dependencies added to our build.gradle file:
Our ViewModel is like:
So, in order to test the above ViewModel, we are going to use MockWebServer of square. First, we are starting with arranging the expected .json responses. We have integrated the following API in our app:
http://dummy.restapiexample.com/api/v1/employees
So, we are adding the following .json files to resources directory which contains simply the success and failed response of the above API.
Moving on to our test package where we will actually write a unit test to test our RequestViewModel. But before that, we have to write the code to read the above .json files.
Now, let’s create the test RequestViewModelTest.kt to test our Retrofit logic present in our RequestViewModel class. In setUp() method let’s initialize mockito, RequestViewModel’s instance, register our observer and the important stuff of this article, initializing MockWebServer and starting the same. With this we also have ApiHelper initialized so that we can actually fetch employee’s details:
Let’s create our first test to check the content of success_response.json file which we have created above, the content should not be null and if we run the following, it has got passed successfully:
In the next test, let’s fetch employee’s details and check if the response code ‘200’ from server matches with the response code present in success_response.json which is our expected response:
Finally, the above test has got passed.
In the next test, let’s fetch status from success_response.json and compare it with the actual status we are getting from the server:
If you notice above, we are calling one method named `parse mocked JSON response`, it basically parses the JSON response present in success_response.json.
And yes, the above test has also got passed, we have got “success” from both.
Finally, in the last don’t forget to stop MockWebServer in tearDown() method and de-register the observer which we registered in setUp() method:
You can find the detailed implementation on the following link:
Thanks for reading this article. If you’ve found this useful, please don’t forget to give us the claps.