Getting ready to test

This is the part where we get our hands dirty. I assume here that you are comfortable with writing basic unit test methods. Your test methods should be kept simple anyway so don’t worry they will be very easy to understand.

For this we will create an api call that performs a login operation. Here I use Retrofit. Again, if you are reading this post, I assume that performing api calls is not new to you.

This AuthenticationManager will be called by an AuthenticationInterceptor to retrieve the token or perform authentication with the hardcoded credentials.

As you can see, the Endpoint is harcoded as a constant but is also required in the constructor. This will become usefull in a second.

Mocking the Http call using MockWebServer

MockWebServer is a library provided by Square that lets you Mock a WebServer. The idea is that you create a mock server and you tell it what it should return when called. So you just pass it a String body and it will return it. This library also lets you inspect the calls it has received (path, params, body…). So we should have all our needs covered.

Before we can use it though, we need an efficient way to store and retrieve body responses. We don’t want to clutter our test classes with enormous json like strings. We want to save those potential responses as json files and read them for our tests.

Reading Test Resources

You start by creating a json file.

And we save it in your test resources directory exactly like this. This is important so that our test resources get picked up by the Android Gradle plugin.

Test resources hierarchy.

Then we need a way to easy access those files.

In this class, we can access the classLoader and read the resources because we placed the resources in the “resources” directory. Otherwise we would have gotten a FileNotFoundException.

As a little bonus, and because we are into testing now ; we are going to test this MockResponseFileReader. This is really easy and will give us confidence that we are on the right track.

We create a quick test.json file that simply contains the word “success” and we test that we can successfully read it.

Testing our testing tools =)

Using a dependency injection framework

This is clearly an optional step, but you will see that we use dependency injection by constructor in our tests so a framework can make our life easier when things become more complex or we need to refactor.

For this project, I have decided to use Koin which is very simple to use. So although it may not have all the cool features that Dagger has, it leaves you with enough brain power to understand the advantages of dependency injection while learning to use it.