简体   繁体   English

Android单元测试

[英]Android unit testing

I want to create unit tests for the main part of my application which is APIcalls.java class. 我想为我的应用程序的主要部分APIcalls.java类创建单元测试。 Is it possible in android to test these kind of requests? 在Android中可以测试这些请求吗? Because every time I call my API get method, I get an error and get nothing from the server. 因为每次我调用API get方法时,都会收到一个错误,并且从服务器中什么也得不到。 Here is the get method: 这是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;

Is it somehow possible to test what kind of data I am receiving from server? 是否可以通过某种方式测试我从服务器接收的数据类型?

The unit test isn't going to have (and really shouldn't need) network access. 单元测试将不会(而且确实不需要)网络访问。 You should simulate the parts that you can simply assume work using dependency injection and a mocking framework like Mockito . 您应该使用依赖注入和类似Mockito的模拟框架来模拟可以简单地承担工作的部分。 Use the mocking framework to ensure you test responses for both successes and failures. 使用模拟框架可确保测试成功和失败的响应。 Try to cover as many types of cases as you might expect in a production environment. 尝试涵盖生产环境中可能需要的多种类型的案例。

Specifically, in this case you may want to inject an AbstractHttpClient. 具体来说,在这种情况下,您可能需要注入AbstractHttpClient。 Then you can mock the execute() method to return exactly the response you need per test, but provide the DefaultHttpClient in production. 然后,您可以模拟execute()方法以精确返回每次测试所需的响应,但在生产环境中提供DefaultHttpClient。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM