使用Robolectric进行Android http测试

我有一个 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中正确测试这个课程?

解决方法

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看到更多的例子.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...