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

Use asInstanceOf[T] carefully!

BackgroundScala has nice static type checking engine but from time to time there are situations when we must downcast some general object. If this casting is not possible we expect that virtual machine will throw ClassCastExeption as fast as possible. ...

Sample for lift-ng: Micro-burn 1.0.0 released

During a last few evenings in my free time I've worked on mini-application called micro-burn. The idea of it appear from work with Agile Jira in our commercial project. This is a great tool for agile projects management. It has inline tasks edition, drag & drop board, reports and many more, but it also have a few drawbacks that turn down our team motivation.

Motivation

From time to time our sprints scope is changing. It is not a big deal because we are trying to be agile :-) but Jira's burndowchart in this situation draw a peek. Because in fact that chart shows scope changes not a real burndown. It means, that chart cannot break down an x-axis if we really do more than we were planned – it always stop on at most zero.

Also for better progress monitoring we've started to split our user stories to technical tasks and estimating them. Original burndowchart doesn't show points from technical tasks. I can find motivation of this – user story almost finished isn't finished at all until user can use it. But in the other hand, if we know which tasks is problematic we can do some teamwork to move it on.

So I realize that it is a good opportunity to try some new approaches and tools.

Tools

I've started with lift framework. In the World of Single Page Applications, this framework has more than simple interface for serving REST services. It comes with awesome Comet support. Comet is a replacement for WebSockets that run on all browsers. It supports long polling and transparent fallback to short polling if limit of client connections exceed. In backend you can handle pushes in CometActor. For further reading take a look at Roundtrip promises

But lift framework is also a kind of framework of frameworks. You can handle own abstraction of CometActors and push to client javascript that shorten up your way from server to client. So it was the trigger for author of lift-ng to make a lift with Angular integration that is build on top of lift. It provides AngularActors from which you can emit/broadcast events to scope of controller. NgModelBinders that synchronize your backend model with client scope in a few lines! I've used them to send project state (all sprints and thier details) to client and notify him about scrum board changes. My actor doing all of this hard work looks pretty small:

Lift-ng also provides factories for creating of Angular services. Services could respond with futures that are transformed to Angular promises in-fly. This is all what was need to serve sprint history:

And on the client side - use of service:


In my opinion this two frameworks gives a huge boost in developing of web applications. You have the power of strongly typing with Scala, you can design your domain on Actors and all of this with simplicity of node.js – lack of json trasforming boilerplate and dynamic application reload.

DDD + Event Sourcing

I've also tried a few fresh approaches to DDD. I've organize domain objects in actors. There are SprintActors with encapsulate sprint aggregate root. Task changes are stored as events which are computed as a difference between two boards states. When it should be provided a history of sprint, next board states are computed from initial state and sequence of events. So I realize that the best way to keep this kind of event sourcing approach tested is to make random tests. This is a test doing random changes at board, calculating events and checking if initial state + events is equals to previously created state:



First look

Screenshot of first version:


If you want to look at this closer, check the source code or download ready to run fatjar on github.During a last few evenings in my free time I've worked on mini-application called micro-burn. The idea of it appear from work with Agile Jira in our commercial project. This is a great tool for agile projects management. It has inline tasks edition, drag & drop board, reports and many more, but it also have a few drawbacks that turn down our team motivation.