我有一堂课:
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) {...}
}
我找不到使用标准框架对其进行测试的方法。特别是,我需要模拟从测试内部丢失的总互联网。
建议在执行测试时手动关闭模拟器中的 Internet。但在我看来,这不是一个很好的解决方案,因为自动测试应该是......自动的。
我在类中添加了一个“客户端”字段,试图从测试类内部模拟它。但是 HttpClient 接口的实现似乎相当复杂。
据我所知, Robolectric框架允许开发人员测试Http 连接。但我想有一些方法可以在不使用这么大的附加框架的情况下编写这样的测试。
那么是否有任何使用 HttpClient 的单元测试类的简单直接的方法?你是如何在你的项目中解决这个问题的?