使用Robolectric进行Android HTTP测试

12

我有一个安卓应用程序,其中最主要的部分是APIcalls.java类,我在该类中进行HTTP请求以获取来自服务器的数据并在应用程序中显示该数据。

我想为这个Java类创建单元测试,因为它是应用程序的主要部分。这是从服务器获取数据的方法:

StringBuilder sb = new StringBuilder();

try {

  httpclient = new DefaultHttpClient(); 
  Httpget httpget = new HttpGet(url);

  HttpEntity entity = null;
  try {
    HttpResponse response = httpclient.execute(httpget);
    entity = response.getEntity();
  } catch (Exception e) {
    Log.d("Exception", e);
  }


  if (entity != null) {
    InputStream is = null;
    is = entity.getContent();

    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));

      while ((line = reader.readLine()) != null) {
       sb.append(line + "\n");
     }
      reader.close();
    } catch (IOException e) {

           throw e;

       } catch (RuntimeException e) {

           httpget.abort();
           throw e;

       } finally {

         is.close();

       }
       httpclient.getConnectionManager().shutdown();
  }
} catch (Exception e) {
  Log.d("Exception", e);
}

String result = sb.toString().trim();

return result;
我以为我可以像这样从测试中发出简单的API调用:
api.get("www.example.com")

但是每次我从测试中发起一些http请求时,都会出现错误:

Unexpected HTTP call GET

我知道我在这里做错了什么,但有谁能告诉我如何在Android中正确地测试这个类?


3个回答

24
感谢您提供的所有答案,但我已经找到了我要找的东西。 我想测试真正的HTTP调用。
通过添加Robolectric.getFakeHttpLayer().interceptHttpRequests(false);, 您告诉Robolectric不要拦截这些请求,并允许您进行真正的HTTP调用。

当调用静态函数getFakeHttpLayer()时,我遇到了编译器错误。看起来它不再是API的一部分,或者我做错了什么。 - Gem
7
使用最新版本的Robolectric 3.0,在build.gradle中添加以下内容: testCompile 'org.robolectric:shadows-httpclient:3.0'然后,您可以使用以下代码: FakeHttp.getFakeHttpLayer().interceptHttpRequests(false);这将关闭拦截HTTP请求的功能。 - Nhat Dinh

7

Robolectric提供了一些帮助方法来模拟DefaultHttpClient的http响应。如果您在不使用这些方法的情况下使用DefaultHttpClient,则会收到警告消息。

以下是如何模拟http响应的示例:

@RunWith(RobolectricTestRunner.class)
public class ApiTest {

    @Test
    public void test() {
        Api api = new Api();
        Robolectric.addPendingHttpResponse(200, "dummy");
        String responseBody = api.get("www.example.com");
        assertThat(responseBody, is("dummy"));
    }
}

您可以查看Robolectric的测试代码来获取更多示例。


0

我之前回答过这个问题的另一个版本,但是...

你所使用的并不是来自Android的任何东西,因此Robolectric基本上是无关紧要的。这都是标准的Java和Apache HTTP库。你只需要一个模拟框架和依赖注入来模拟HttpClient(请参见我的其他答案中的链接)。在单元测试时,它没有网络访问,因此会失败。

当测试使用Android框架的部分类时,你可以使用Robolectric(或类似工具)来模拟或模拟Android.jar,因为你的单元测试框架也无法访问它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接