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
I need deep explanation about RoboGuice Tutorials in English. When translated, the meaning of the sentences is changing over.
OdpowiedzUsuń