Mock Retrofit using Dagger and Mockito

Retrofit is one of the most popular REST client for Android, if you never use it, it is high time to start. There are a lot of articles and tutorial talking about Retrofit. I just would like to show how to mock a REST server during develop of app and i…Retrofit is one of the most popular REST client for Android, if you never use it, it is high time to start. There are a lot of articles and tutorial talking about Retrofit. I just would like to show how to mock a REST server during develop of app and i…

Retrofit is one of the most popular REST client for Android, if you never use it, it is high time to start. There are a lot of articles and tutorial talking about Retrofit. I just would like to show how to mock a REST server during develop of app and in unit test when you are using Dagger as DI.

The example app will query the Echo REST serwer with:
http://echo.jsontest.com/message/sample_message/quantity/11the server responds with

{
    "message": "sample_message",
    "quantity": "11"
}

ApplicationI suggest to no using TDD this time and start from the app. Let’s look at the most significant part of implementation.

  • Interface of the service accordingly with Retrofit convention:
    public interface EchoService {
        @Headers("Content-Type: form-urlencoded; charset=utf-8")
        @GET("/message/{message}/quantity/{quantity}")
        EchoResponse getMessageAndQuantity(
                @Path("message") String message, 
                @Path("quantity") int quantity
        );
    }
  • Dagger provider that provides Retrofit service adapter
    @Module(
            injects = MainActivity.class,
            library = true,
            complete = false
    )
    public class RestServicesModule {
    
        @Provides
        @Named("realService")
        EchoService provideLogoutService() {
            return new RestAdapter.Builder()
                    .setServer("http://echo.jsontest.com")
                    .build()
                    .create(EchoService.class);
        }
    }

    As you can see I have also add @Named annotation. Of course it is not obligatory but I use it to inject real and mocked adapter, both in the same class. Check out the whole example on my Github to find out what I mean.

  • A piece of code that makes the query
@Inject
@Named("realService")
EchoService realService;

//some code

@Override
protected EchoResponse doInBackground(Void... params) {
    return realService.getMessageAndQuantity("example", "32");
}

In that way we make a call to server synchronously. It is not the most sophisticated example I can imagine, but the simplest showing how it works.

During develop of app I often would like to mock the server to get some kind of response (for example to check apps behaviour in some corner case) or just develop though server is down. Moreover it would be nice to be able to turn off/on mock in very simple and fast way.Thus I have write second Dagger module that provides mocked service adapter:

@Module(
        injects = MainActivity.class,
        library = true,
        complete = false
)
public class RestServicesMockModule {

    @Provides
    @Named("mockService")
    EchoService provideLogoutService(Client client) {
        return new RestAdapter.Builder()
                .setServer("http://echo.jsontest.com")
                .setClient(client)
                .build()
                .create(EchoService.class);
    }

    @Provides
    @Singleton
    Client provideMockClient() {
        return new RetrofitClientMock();
    }
}

//You certain noticed additional piece of code that set the Retrofit Client - in a nutshell the Client handle communication over the Internet. Thus we pass custom implementation of client. To keep clarify, implementation of the custom CLient is as simple as possible - always return the same response:
public class RetrofitClientMock implements Client {

    private static final int HTTP_OK_STATUS = 200;

    private static final String LOGIN_VALID_RESP = "{\n"
            + " \"message\": \"mock message\",\n"
            + " \"quantity\": \"11\"\n"
            + "}";

    @Override
    public Response execute(Request request) throws IOException {
        return createResponseWithCodeAndJson(HTTP_OK_STATUS, LOGIN_VALID_RESP);
    }

    private Response createResponseWithCodeAndJson(int responseCode, String json) {
        return new Response(responseCode, "nothing", Collections.EMPTY_LIST,
                new TypedByteArray("application/json", json.getBytes()));
    }
}
//You can activate the mock by adding the mock module to Dagger injector initialization.

Unit TestsDuring develop of app, you can send requests the server all time(or most of time) so it is possible to live without mocked serwer, it sucks but is possible. Unfortunately you are not able to write good tests without the mock. Below there are two unit tests. Actually they do not test anything but in simple way shows how to mock Retrofit service using Mockito and Dagger.

@RunWith(RobolectricTestRunner.class)
public class EchoServiceTest {

    @Inject
    protected EchoService loginService;

    @Inject
    protected Client client;

    @Before
    public void setUp() throws Exception {
        Injector.add(new AndroidModule(),
                new RestServicesModule(),
                new RestServicesMockModule(),
                new TestModule());
        Injector.inject(this);
    }

    @Test
    public void shouldReturnOfferInAsyncMode() throws IOException {
//given
        int expectedQuantity = 765;
        String responseContent = "{" +
                " \"message\": \"mock message\"," +
                " \"quantity\": \"" + expectedQuantity + "\"" +
                "}";
        mockResponseWithCodeAndContent(200, responseContent);

//when
        EchoResponse echoResponse = loginService.getMessageAndQuantity("test", "test");

//then
        assertThat(echoResponse.getQuantity()).isEqualTo(expectedQuantity);
    }

    @Test
    public void shouldReturnOfferInAsyncModea() throws IOException {
//given
        int expectedQuantity = 2;
        String responseContent = "{" +
                " \"message\": \"mock message\"," +
                " \"quantity\": \"" + expectedQuantity + "\"" +
                "}";
        mockResponseWithCodeAndContent(200, responseContent);

//when
        EchoResponse echoResponse = loginService.getMessageAndQuantity("test", "test");

//then
        assertThat(echoResponse.getQuantity()).isEqualTo(expectedQuantity);
    }


    protected void mockResponseWithCodeAndContent(int httpCode, String content) throws IOException {
        Response response = createResponseWithCodeAndJson(httpCode, content);
        when(client.execute(Matchers.anyObject())).thenReturn(response);
    }

    private Response createResponseWithCodeAndJson(int responseCode, String json) {
        return new Response(responseCode, "nothing", Collections.EMPTY_LIST, new TypedByteArray("application/json", json.getBytes()));
    }
}

And Dagger module for the tests:

@Module(
        injects = OfferDetailAdapterTest.class,
        overrides = true,
        library = true,
        complete = false

)
public class TestModule {

    @Provides
    EchoService provideLogoutService(Client client) {
        return new RestAdapter.Builder().setServer("http://echo.jsontest.com").setClient(client).build().create(EchoService.class);
    }

    @Provides
    @Singleton
    Client provideMockClient() {
        return mock(Client.class);
    }
}

 

Please notice very important detail. The mock Client provider method is annotated with @Singleton, it is obligatory to successfully mock the server in Test. If you miss @Singleton, then in runtime, there will be two instances of Client class. One in Test and another in instance of Activity class. Thus you operations on the client in Test class will have not any influence for behaviour in tested class.

The source code of the example you can find on my Github

You May Also Like

Spock, Java and Maven

Few months ago I've came across Groovy - powerful language for JVM platform which combines the power of Java with abilities typical for scripting languages (dynamic typing, metaprogramming).

Together with Groovy I've discovered spock framework (https://code.google.com/p/spock/) - specification framework for Groovy (of course you can test Java classes too!). But spock is not only test/specification framework - it also contains powerful mocking tools.

Even though spock is dedicated for Groovy there is no problem with using it for Java classes tests. In this post I'm going to describe how to configure Maven project to build and run spock specifications together with traditional JUnit tests.


Firstly, we need to prepare pom.xml and add necessary dependencies and plugins.

Two obligatory libraries are:
<dependency>
<groupid>org.spockframework</groupId>
<artifactid>spock-core</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
<version>${groovy.version}</version>
<scope>test</scope>
</dependency>
Where groovy.version is property defined in pom.xml for more convenient use and easy version change, just like this:
<properties>
<gmaven-plugin.version>1.4</gmaven-plugin.version>
<groovy.version>2.1.5</groovy.version>
</properties>

I've added property for gmaven-plugin version for the same reason ;)

Besides these two dependencies, we can use few additional ones providing extra functionality:
  • cglib - for class mocking
  • objenesis - enables mocking classes without default constructor
To add them to the project put these lines in <dependencies> section of pom.xml:
<dependency>
<groupid>cglib</groupId>
<artifactid>cglib-nodep</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.objenesis</groupId>
<artifactid>objenesis</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>

And that's all for dependencies section. Now we will focus on plugins necessary to compile Groovy classes. We need to add gmaven-plugin with gmaven-runtime-2.0 dependency in plugins section:
<plugin>
<groupid>org.codehaus.gmaven</groupId>
<artifactid>gmaven-plugin</artifactId>
<version>${gmaven-plugin.version}</version>
<configuration>
<providerselection>2.0</providerSelection>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupid>org.codehaus.gmaven.runtime</groupId>
<artifactid>gmaven-runtime-2.0</artifactId>
<version>${gmaven-plugin.version}</version>
<exclusions>
<exclusion>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
<version>${groovy.version}</version>
</dependency>
</dependencies>
</plugin>

With these configuration we can use spock and write our first specifications. But there is one issue: default settings for maven-surefire plugin demand that test classes must end with "..Test" postfix, which is ok when we want to use such naming scheme for our spock tests. But if we want to name them like CommentSpec.groovy or whatever with "..Spec" ending (what in my opinion is much more readable) we need to make little change in surefire plugin configuration:
<plugin>
<groupid>org.apache.maven.plugins</groupId>
<artifactid>maven-surefire-plugin</artifactId>
<version>2.15</version>
<configuration>
<includes>
<include>**/*Test.java</include>
<include>**/*Spec.java</include>
</includes>
</configuration>
</plugin>

As you can see there is a little trick ;) We add include directive for standard Java JUnit test ending with "..Test" postfix, but there is also an entry for spock test ending with "..Spec". And there is a trick: we must write "**/*Spec.java", not "**/*Spec.groovy", otherwise Maven will not run spock tests (which is strange and I've spent some time to figure out why Maven can't run my specs).

Little update: instead of "*.java" postfix for both types of tests we can write "*.class" what is in my opinion more readable and clean:
<include>**/*Test.class</include>
<include>**/*Spec.class</include>
(thanks to Tomek Pęksa for pointing this out!)

With such configuration, we can write either traditional JUnit test and put them in src/test/java directory or groovy spock specifications and place them in src/test/groovy. And both will work together just fine :) In one of my next posts I'll write something about using spock and its mocking abilities in practice, so stay in tune.