1

我想为我的应用程序的主要部分创建单元测试,即 APIcalls.java 类。是否可以在 android 中测试此类请求?因为每次我调用我的 API get 方法时,我都会收到一个错误并且从服务器上什么也得不到。这是get方法:

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;

是否有可能测试我从服务器接收到的数据类型?

4

1 回答 1

0

单元测试不会(并且实际上不需要)网络访问。您应该使用依赖注入Mockito 之类的模拟框架来模拟您可以简单假设工作的部分。使用模拟框架确保您测试成功和失败的响应。尝试在生产环境中涵盖尽可能多的案例类型。

具体来说,在这种情况下,您可能想要注入 AbstractHttpClient。然后,您可以模拟 execute() 方法以准确返回每次测试所需的响应,但在生产中提供 DefaultHttpClient。

于 2013-09-17T15:07:29.677 回答