【问题标题】:Testing http request/response in android在android中测试http请求/响应
【发布时间】:2014-01-06 19:14:23
【问题描述】:

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

有什么方法可以模拟 rest 模板发送的 HTTP 请求吗?我可以提供我喜欢的回答吗?

【问题讨论】:

标签: android


【解决方案1】:

是的,我正在执行以下操作:

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

androidTestCompile("org.springframework:spring-test:3.2.8.RELEASE") {
    exclude module: "spring-core"
}

您希望排除以避免此异常

java.lang.IllegalAccessError:预验证类中的类引用已解决 到意想不到的实施

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

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
}

这是来自 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();

另一种方法是使用 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"

您需要以上各项才能正确使用 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);

    }
}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    相关资源
    最近更新 更多