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 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/11
the server responds with
{
"message": "sample_message",
"quantity": "11"
}

Application

I 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 Tests

During 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

Phonegap / Cordova and cross domain ssl request problem on android.

In one app I have participated, there was a use case:
  • User fill up a form.
  • User submit the form.
  • System send data via https to server and show a response.
During development there wasn’t any problem, but when we were going to release production version then some unsuspected situation occurred. I prepare the production version accordingly with standard flow for Android environment:
  • ant release
  • align
  • signing
During conduct tests on that version, every time I try to submit the form, a connection error appear. In that situation, at the first you should check whitelist in cordova settings. Every URL you want to connect to, must be explicit type in:
res/xml/cordova.xml
If whitelist looks fine, the error is most likely caused by inner implementation of Android System. The Android WebView does not allow by default self-signed SSL certs. When app is debug-signed the SSL error is ignored, but if app is release-signed connection to untrusted services is blocked.



Workaround


You have to remember that secure connection to service with self-signed certificate is risky and unrecommended. But if you know what you are doing there is some workaround of the security problem. Behavior of method
CordovaWebViewClient.onReceivedSslError
must be changed.


Thus add new class extended CordovaWebViewClient and override ‘onReceivedSslError’. I strongly suggest to implement custom onReceiveSslError as secure as possible. I know that the problem occours when app try connect to example.domain.com and in spite of self signed certificate the domain is trusted, so only for that case the SslError is ignored.

public class MyWebViewClient extends CordovaWebViewClient {

   private static final String TAG = MyWebViewClient.class.getName();
   private static final String AVAILABLE_SLL_CN
= "example.domain.com";

   public MyWebViewClient(DroidGap ctx) {
       super(ctx);
   }

   @Override
   public void onReceivedSslError(WebView view,
SslErrorHandler handler,
android.net.http.SslError error) {

String errorSourceCName = error.getCertificate().
getIssuedTo().getCName();

       if( AVAILABLE_SLL_CN.equals(errorSourceCName) ) {
           Log.i(TAG, "Detect ssl connection error: " +
error.toString() +
„ so the error is ignored”);

           handler.proceed();
           return;
       }

       super.onReceivedSslError(view, handler, error);
   }
}
Next step is forcing yours app to  use custom implementation of WebViewClient.

public class Start extends DroidGap
{
   private static final String TAG = Start.class.getName();

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       super.setIntegerProperty("splashscreen", R.drawable.splash);
       super.init();

       MyWebViewClient myWebViewClient = new MyWebViewClient(this);
       myWebViewClient.setWebView(this.appView);

       this.appView.setWebViewClient(myWebViewClient);
       
// yours code

   }
}
That is all ypu have to do if minSdk of yours app is greater or equals 8. In older version of Android there is no class
android.net.http.SslError
So in class MyCordovaWebViewClient class there are errors because compliator doesn’t see SslError class. Fortunately Android is(was) open source, so it is easy to find source of the class. There is no inpediments to ‘upgrade’ app and just add the file to project. I suggest to keep original packages. Thus after all operations the source tree looks like:

Class SslError placed in source tree. 
 Now the app created in release mode can connect via https to services with self-signed SSl certificates.