У меня есть класс:
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 true.
* @return 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.
*/
public String readWebResource(String path, ArrayList 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) {...}
}
Я не могу найти способ протестировать его, используя стандартную структуру. В частности, мне нужно смоделировать полную потерю интернета внутри теста.
Есть предложения вручную отключать интернет в эмуляторе при тестировании, но мне кажется это не совсем удачным решением, потому что автоматические тесты должны быть... автоматическими
Я добавил "клиент"
Среда Robolectricпозволяет разработчикам тестировать Http-соединениекак насколько я знаю. Но я предполагаю, что есть какой-то способ написать такой тест, не используя такой большой дополнительный фреймворк.
Итак, есть ли короткие и простые способы модульного тестирования классов, использующих HttpClient? Как вы решили это в своем проекты?