在android中测试http请求/响应

Arm*_*men 5 android

在我的Android应用程序中,我正在使用Sprint Rest Template对Web服务器进行API调用.但是在测试项目中,我测试了使用String ResT Template发出请求的方法,我不想发送真正的HTTP请求.

有没有办法模拟休息模板发送的HTTP请求?我可以提供我的首选回复吗?

vin*_*501 6

是的,我正在做类似以下的事情:

在build.gradle中添加以下内容:

androidTestCompile("org.springframework:spring-test:3.2.8.RELEASE") {
    exclude module: "spring-core"
}
Run Code Online (Sandbox Code Playgroud)

您希望排除以避免此异常

java.lang.IllegalAccessError:预验证类中的类ref已解析为意外实现

然后在您的测试中执行以下操作:

public void testService() throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        PeopleService peopleService = new PeopleService(restTemplate);

        MockRestServiceServer mockServer = 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));

        People people = peopleService.getPeople();

        mockServer.verify();

        assertThat(people).isNotNull();
        //Other assertions
}
Run Code Online (Sandbox Code Playgroud)

以下是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();
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用Mockito.在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"
Run Code Online (Sandbox Code Playgroud)

您需要以上各项才能正确使用Mockito.

然后在您的测试中执行以下操作:

public class TestClass extends InstrumentationTestCase {
    @Mock
    private RestTemplate restTemplate;

    protected void setUp() throws Exception {
        super.setUp();

        initMocks(this);
    }

    public void testWithMockRestTemplate() throws Exception {
        Hotel expectedHotel = new Hotel("Fake Hotel From Mocked Rest Template");
        when(restTemplate.getForObject("/hotels/{id}", Hotel.class, 42).thenReturn(expectedHotel);

        Hotel hotel = restTemplate.getForObject("/hotels/{id}", Hotel.class, 42);

        assertThat(hotel).isEqualTo(expectedHotel);

    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!