我有一个安卓应用程序,其中最主要的部分是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中正确地测试这个类?