android - 如何使用内置框架对在 Android 中使用 HttpClient 的类进行单元测试?

标签 android unit-testing httpclient

我有一个类:

public class WebReader implements IWebReader {

    HttpClient client;

    public WebReader() {
        client = new DefaultHttpClient();
    }

    public WebReader(HttpClient httpClient) {
        client = httpClient;
    }

    /**
     * Reads the web resource at the specified path with the params given.
     * @param path Path of the resource to be read.
     * @param params Parameters needed to be transferred to the server using POST method.
     * @param compression If it's needed to use compression. Default is <b>true</b>.
     * @return <p>Returns the string got from the server. If there was an error downloading file, 
     * an empty string is returned, the information about the error is written to the log file.</p>
     */
    public String readWebResource(String path, ArrayList<BasicNameValuePair> params, Boolean compression) {
            HttpPost httpPost = new HttpPost(path);
            String result = "";

            if (compression)
                httpPost.addHeader("Accept-Encoding", "gzip");
            if (params.size() > 0){
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
            }

            try {
                HttpResponse response = client.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    if (entity.getContentEncoding() != null
                            && "gzip".equalsIgnoreCase(entity.getContentEncoding()
                                    .getValue()))
                        result = uncompressInputStream(content);
                    else
                        result = convertStreamToString(content);
                } else {
                    Log.e(MyApp.class.toString(), "Failed to download file");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return result;
        }

    private String uncompressInputStream(InputStream inputStream)
            throws IOException {...}

    private String convertStreamToString(InputStream is) {...}

}

我找不到使用标准框架对其进行测试的方法。特别是,我需要在测试中模拟整个互联网丢失。

有建议在执行测试时手动关闭模拟器中的互联网。但在我看来这不是一个很好的解决方案,因为自动测试应该是……自动的。

我在类中添加了一个“client”字段,试图从测试类内部模拟它。但是HttpClient接口(interface)的实现似乎相当复杂。

Robolectric框架允许开发人员测试 Http connection据我所知。但我想有一些方法可以在不使用这么大的额外框架的情况下编写这样的测试。

那么有没有什么简单直接的方法可以对使用 HttpClient 的类进行单元测试呢?您是如何在您的项目中解决这个问题的?

最佳答案

I added a "client" field to the class trying to mock it from inside the test class. But implementation of the HttpClient interface seems quite complex.

我对这个说法有点困惑。从问题标题来看,您是在询问有关单元测试 httpClint 的问题,通过模拟 FakeHttpClient 可能会帮助您对除 httpClient 之外的应用程序的其他部分进行单元测试,但对单元测试 httpClient 没有任何帮助。您需要的是用于对 httpClient 进行单元测试的 FakeHttpLayer(没有远程服务器,需要网络,因此需要进行单元测试)。

HttpClient 虚拟测试:

如果您只需要在网络丢失的情况下检查应用程序行为,那么经典的 Android Instrument Test 就足够了,您可以在执行测试时以编程方式在模拟器中关闭网络:

public void testWhenInternetOK() {
  ... ...
  webReader.readWebResource();
  // expect HTTP 200 response.
  ... ...
}

public void testWhenInternetLost() {
  ... ...
  wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
  wifiManager.setWifiEnabled(false);
  webReader.readWebResource();
  // expect no HTTP response.
... ...
}

这需要远程 http 服务器已完全设置并处于工作状态,并且无论何时运行测试类,都会通过网络进行真正的 http 通信并访问 http 服务器。

HttpClient 高级测试:

如果您想更精确地测试应用程序行为,例如,您想要在您的应用程序中测试一个 http 调用,看看它是否正确处理了不同的 http 响应。 Robolectric 是最佳选择。您可以使用 FakeHttpLayer 并根据您的喜好模拟 http 请求和响应。

public void setup() {
  String url = "http://...";
  // First http request fired in test, mock a HTTP 200 response (ContentType: application/json)
  HttpResponse response1 = new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_1, 200, null);
  BasicHttpEntity entity1 = new BasicHttpEntity();
  entity1.setContentType("application/json");
  response1.setEntity(entity1);
  // Second http request fired in test, mock a HTTP 404 response (ContentType: text/html)
  HttpResponse response2 = new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_1, 404, null);
  BasicHttpEntity entity2 = new BasicHttpEntity();
  entity2.setContentType("text/html");
   response2.setEntity(entity2);
  List<HttpResponse> responses = new ArrayList<HttpResponse>();
  responses.add(response1);
  responses.add(response2);
  Robolectric.addHttpResponseRule(new FakeHttpLayer.UriRequestMatcher("POST", url), responses);
}

public void testFoo() {
  ... ...
  webReader.readWebResource(); // <- a call that perform a http post request to url.
  // expect HTTP 200 response.
  ... ...
}

public void testBar() {
  ... ...
  webReader.readWebResource(); // <- a call that perform a http post request to url.
  // expect HTTP 404 response.
... ...
}

使用 Robolectric 的一些优点是:

  • 纯JUnit测试,无仪器测试,无需启动模拟器(或真机)运行测试,提高开发速度。
  • 最新的 Robolectric 支持单行代码来启用/禁用 FakeHttpLayer,您可以在其中设置要由 FakeHttpLayer 解释的 http 请求(没有真正的网络 http 调用),或者设置 http 请求绕过 FakeHttpLayer(执行真正的 http 调用)网络)。查看this SO question了解更多详情。

如果查看 Robolectric 的源代码,您会发现自己正确实现 FakeHtppLayer 非常复杂。我建议使用现有的测试框架,而不是实现您自己的 API。

希望这对您有所帮助。

关于android - 如何使用内置框架对在 Android 中使用 HttpClient 的类进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10136682/

相关文章:

c# - 模拟服务调用对象返回 null

unit-testing - 有没有办法在 Rust 中构建测试以在不详尽时发出警告?

android - (Android) 线程化的 httpClient 任务,不阻塞 UI?

kotlin - 如何在 ktor-client 中禁用重定向

android - Google Pay 不显示总价或 displayItems

Android将多个文件从sdcard附加到电子邮件

Android Make Disappear 或去除 map 上的蓝点 v2

java - sharedPref.getInt : java. lang.String 无法转换为 java.lang.Integer

javascript - 当没有找到测试时,Mocha 会抛出一个错误。这能被压制吗?

java - 如何在java中将响应解析为JSON