【发布时间】:2017-01-10 22:57:33
【问题描述】:
我正在使用最新发布的 Robolectric (3.1.2) 版本。
我正在为依赖 API 的应用编写测试,因此我确实需要确保该 API 有效。
我能够发出不需要模拟响应的 http 请求调用。但是当我确实需要调用模拟响应时,这就是我如何获取模拟响应的问题。
当我尝试模拟响应时,我总是得到默认的 http 响应,而不是我想要得到的字符串响应。
我一直在谷歌搜索如何模拟 http 响应,我已经尝试了尽可能多的建议,但我无法让它发挥作用。
非常感谢任何建议,因为我在这里抓住了稻草。
这是我正在使用的 gradle 和测试用例
build.gradle
testCompile 'junit:junit:4.12'
testCompile 'org.robolectric:robolectric:3.1.2'
testCompile 'org.robolectric:shadows-multidex:3.1.2'
testCompile 'org.robolectric:shadows-httpclient:3.1.2'
Test case
@Before
public void setup() {
FakeHttp.getFakeHttpLayer().interceptHttpRequests(false);
}
@Test
public void VerifyAwwYeeaaahhhTest() {
mainActivity = Robolectric.buildActivity(MainActivity.class).create().visible().get();
shadowMain = Shadows.shadowOf(mainActivity);
FakeHttp.getFakeHttpLayer().interceptResponseContent(false);
String url = "https://example.com";
FakeHttp.setDefaultHttpResponse(200, "Awwwwww yeeeeaaaaahhhh");
try {
DefaultHttpClient client = new DefaultHttpClient();
mHttpGetMock = new HttpGet(url);
mHttpGetMock.addHeader("Authroization", "12345imatoken67890");
mHttpGetMock.addHeader("Accept-Encoding", "G-Zip");
mHttpResponseMock = client.execute(mHttpGetMock);
assertEquals("Awwwwww yeeeeaaaaahhhh", mHttpResponseMock);
System.out.println("Successful Aww yeeaah Test");
} catch (UnsupportedEncodingException e) {
System.out.println("Unsuccessful Aww yeeaah Test. Unsupported Encoding Exception thrown");
System.out.println(e);
} catch (ClientProtocolException e) {
System.out.println("Unsuccessful Aww yeeaah Test. Client Protocol Exception thrown");
System.out.println(e);
} catch (IOException e) {
System.out.println("Unsuccessful Aww yeeaah Test. IO Exception thrown");
System.out.println(e);
}
}
【问题讨论】:
标签: java android unit-testing http robolectric