Testing Http Request/response In Android
In my android application I'm using Sprint Rest Template for making API call to the webserver. But in test project where I test method for making requests with String ResT Template
Solution 1:
Yes, I'm doing something like the following:
In your build.gradle add the following:
androidTestCompile("org.springframework:spring-test:3.2.8.RELEASE") {
exclude module: "spring-core"
}
You want the exclusion to avoid this exception
java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
Then in your test do something like the following:
publicvoidtestService()throws Exception {
RestTemplaterestTemplate=newRestTemplate();
PeopleServicepeopleService=newPeopleService(restTemplate);
MockRestServiceServermockServer= MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("http://localhost:3000/api/v1-DEV/people"))
.andExpect(method(HttpMethod.GET))
.andExpect(header("Authorization", "Bearer TEST_TOKEN"))
.andRespond(withSuccess("JSON DATA HERE", MediaType.APPLICATION_JSON));
Peoplepeople= peopleService.getPeople();
mockServer.verify();
assertThat(people).isNotNull();
//Other assertions
}
Here is an example from Spring (http://docs.spring.io/spring/docs/3.2.7.RELEASE/javadoc-api/org/springframework/test/web/client/MockRestServiceServer.html):
RestTemplate restTemplate = new RestTemplate()
MockRestServiceServer mockServer =MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("/hotels/42")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("{ \"id\" : \"42\", \"name\" : \"Holiday Inn\"}", MediaType.APPLICATION_JSON));
Hotel hotel = restTemplate.getForObject("/hotels/{id}", Hotel.class, 42);
// Use the hotel instance...
mockServer.verify();
Another way to do it is by using Mockito. Include the following in your build.gradle:
androidTestCompile "com.google.dexmaker:dexmaker:1.0"
androidTestCompile "com.google.dexmaker:dexmaker-mockito:1.0"
androidTestCompile "org.mockito:mockito-core:1.9.5"
You'll need each of the above to use Mockito properly.
Then in your test do the following:
publicclassTestClassextendsInstrumentationTestCase {
@Mockprivate RestTemplate restTemplate;
protectedvoidsetUp()throws Exception {
super.setUp();
initMocks(this);
}
publicvoidtestWithMockRestTemplate()throws Exception {
HotelexpectedHotel=newHotel("Fake Hotel From Mocked Rest Template");
when(restTemplate.getForObject("/hotels/{id}", Hotel.class, 42).thenReturn(expectedHotel);
Hotelhotel= restTemplate.getForObject("/hotels/{id}", Hotel.class, 42);
assertThat(hotel).isEqualTo(expectedHotel);
}
}
Hope this helps!
Post a Comment for "Testing Http Request/response In Android"