私はクラスを持っています:
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) {...}
}
標準フレームワークを使用してテストする方法が見つかりません。特に、テスト内で失われたインターネットの合計をシミュレートする必要があります。
テストの実行中に、エミュレーターでインターネットを手動でオフにすることをお勧めします。しかし、自動テストは自動でなければならないので、それはあまり良い解決策ではないように思えます。
クラスに「クライアント」フィールドを追加して、テストクラス内からモックしようとしました。しかし、HttpClient インターフェースの実装は非常に複雑に見えます。
私の知る限り、 Robolectricフレームワークを使用すると、開発者はHTTP 接続をテストできます。しかし、それほど大きな追加フレームワークを使用せずに、そのようなテストを作成する方法がいくつかあると思います。
では、HttpClient を使用するクラスを単体テストするための短くて簡単な方法はありますか? プロジェクトでこれをどのように解決しましたか?