【问题标题】:Android http testing with Robolectric使用 Robolectric 进行 Android http 测试
【发布时间】:2013-09-15 19:09:17
【问题描述】:

我有一个 Android 应用程序,该应用程序的主要部分是 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 中正确测试这个类?

【问题讨论】:

标签: android robolectric android-testing


【解决方案1】:

感谢您的所有回答,但我找到了我想要的东西。 我想测试真正的 HTTP 调用。

通过添加Robolectric.getFakeHttpLayer().interceptHttpRequests(false); 你告诉 Robolectric 不要拦截这些请求,它允许你进行真正的 HTTP 调用

【讨论】:

  • 调用静态函数 getFakeHttpLayer() 时出现编译器错误。看起来它不再是 api 的一部分,或者我做错了什么。
  • @Gem 使用最新版本的 Robolectric 3.0,将这个添加到 build.gradle testCompile 'org.robolectric:shadows-httpclient:3.0' 然后就可以使用:FakeHttp.getFakeHttpLayer().interceptHttpRequests(false);
【解决方案2】:

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's test codes 找到更多示例。

【讨论】:

    【解决方案3】:

    我回答了同一个问题的另一个版本,但是...

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多