我想使用 Robolectric 2.3-SNAPSHOT 测试一个将在后台执行请求的对象。为了隔离它,我试图模拟返回的 HttpResponse,但是经过几个小时的尝试仍然没有成功。
我创建了一个项目,任何人都可以克隆它。只需运行./gradlew check https://github.com/Maragues/RobolectricDummyProject (git clone https://github.com/Maragues/RobolectricDummyProject.git)
我尝试了:
Robolectric.setDefaultHttpResponse(200,“my_mocked_word”);
MockWebServer (https://code.google.com/p/mockwebserver/)
但测试失败,因为它们查询了真实的 URL。
private static final String MOCKED_WORD = "MOCKED";
@Test
public void mockedRequestUsingMockServer() throws Exception {
mMockWebServer.enqueue(new MockResponse().setBody(MOCKED_WORD));
mMockWebServer.play();
Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
Robolectric.getFakeHttpLayer().interceptResponseContent(false);
String result = request.loadDataFromNetwork();
assertEquals(MOCKED_WORD, result);
}
@Test
public void mockedRequestUsingRobolectric() throws Exception {
Robolectric.setDefaultHttpResponse(200, MOCKED_WORD);
String result = request.loadDataFromNetwork();
assertEquals(MOCKED_WORD, result);
}
执行请求的代码
public String loadDataFromNetwork() throws Exception {
// With Uri.Builder class we can build our url is a safe manner
Uri.Builder uriBuilder = Uri.parse("http://robospice-sample.appspot.com/reverse").buildUpon();
uriBuilder.appendQueryParameter("word", word);
String url = uriBuilder.build().toString();
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url)
.openConnection();
String result = IOUtils.toString(urlConnection.getInputStream());
urlConnection.disconnect();
return result;
}
可能相关的问题:
- 无法使用Robolectric捕获HTTP请求(我尝试过但没有成功。也许我遗漏了什么)
- 有人成功地使用Robolectric模拟HttpRequests吗?(我不使用Eclipse)