Android的HTTP测试与Robolectric [英] Android http testing with Robolectric

查看:208
本文介绍了Android的HTTP测试与Robolectric的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用程序,其中应用程序的主要部分是APIcalls.java类,我发出HTTP请求来从服务器上的数据在应用程序中显示的数据。

I have an Android app where the main part of the app is the APIcalls.java class where I make http requests to get data from server an display the data in the app.

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

I wanted to create unit test for this Java class since it's the most part of the app. Here is the method for getting the data from server:

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调用:

I thought I can make simple API calls from the tests like this:

api.get("www.example.com")

但每次我做的一些测试HTTP调用,我得到一个错误:

But every time I make some http calls from the tests, I get an error:

Unexpected HTTP call GET

我知道我在这里做得不对,但任何人都可以告诉我,我该怎么正确地在Android中测试这个类?

I know I am doing something wrong here, but can anyone tell me how can I properly test this class in Android?

推荐答案

Robolectric提供了一些辅助方法来模拟对DefaultHttpClient HTTP响应。如果你使用DefaultHttpClient不使用这些方法,你会得到一个警告消息。

Robolectric provides some helper methods to mock http response for DefaultHttpClient. If you use DefaultHttpClient without using those methods, you would get a warning message.

下面是如何嘲笑HTTP响应的例子:

Here is an example of how to mock http response:

@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"));
    }
}

您可以通过查看<一找到更多的例子href="https://github.com/robolectric/robolectric/blob/robolectric-2.1.1/src/test/java/org/robolectric/shadows/DefaultRequestDirectorTest.java"相对=nofollow> Robolectric的测试codeS 。

这篇关于Android的HTTP测试与Robolectric的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆