简体   繁体   English

使用Robolectric进行Android http测试

[英]Android http testing with Robolectric

I have an Android app where the main part of the app is the APIcalls.java class where I make http requests to get data from server an display the data in the app. 我有一个Android应用程序,其中应用程序的主要部分是APIcalls.java类,我在其中发出http请求以从服务器获取数据并显示应用程序中的数据。

I wanted to create unit test for this Java class since it's the most part of the app. 我想为这个Java类创建单元测试,因为它是应用程序的大部分内容。 Here is the method for getting the data from server: 以下是从服务器获取数据的方法:

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;

I thought I can make simple API calls from the tests like this: 我以为我可以通过这样的测试进行简单的API调用:

api.get("www.example.com")

But every time I make some http calls from the tests, I get an error: 但是每次我从测试中调用一些http调用时,都会出错:

Unexpected HTTP call GET

I know I am doing something wrong here, but can anyone tell me how can I properly test this class in Android? 我知道我在这里做错了什么,但有谁能告诉我如何在Android中正确测试这个类?

Thank you for all your answers but I found what I was looking for. 谢谢你的所有答案,但我找到了我想要的东西。 I wanted to test real HTTP calls. 我想测试真正的HTTP调用。

By adding Robolectric.getFakeHttpLayer().interceptHttpRequests(false); 通过添加Robolectric.getFakeHttpLayer().interceptHttpRequests(false); you tell Robolectric not to intercept these requests and it allows you to make real HTTP calls 你告诉Robolectric不要拦截这些请求,它允许你进行真正的HTTP调用

Robolectric provides some helper methods to mock http response for DefaultHttpClient. Robolectric提供了一些帮助方法来模拟DefaultHttpClient的http响应。 If you use DefaultHttpClient without using those methods, you would get a warning message. 如果在不使用这些方法的情况下使用DefaultHttpClient,则会收到警告消息。

Here is an example of how to mock http response: 以下是如何模拟http响应的示例:

@RunWith(RobolectricTestRunner.class)
public class ApiTest {

    @Test
    public void test() {
        Api api = new Api();
        Robolectric.addPendingHttpResponse(200, "dummy");
        String responseBody = api.get("www.example.com");
        assertThat(responseBody, is("dummy"));
    }
}

You can find more examples by looking at Robolectric's test codes . 您可以通过查看Robolectric的测试代码找到更多示例。

I answered another version of this same question, but... 我回答了同一个问题的另一个版本,但......

What you have here is not using anything from Android, so Robolectric is basically irrelevant. 你在这里没有使用Android的任何东西,所以Robolectric基本上是无关紧要的。 This is all standard Java and the Apache HTTP library. 这是所有标准Java和Apache HTTP库。 You simply need a mocking framework and dependency injection to simulate the HttpClient (see my other answer for links). 您只需要一个模拟框架和依赖注入来模拟HttpClient(请参阅我的其他链接答案)。 It doesn't have network access while unit testing, and so it fails. 它在单元测试时没有网络访问权限,因此失败了。

When testing classes that use parts of the Android framework, you can use Robolectric (or similar) to mock or simulate Android.jar since your unit testing framework isn't going to have access to that either. 在测试使用Android框架部分的类时,您可以使用Robolectric(或类似的)来模拟或模拟Android.jar,因为您的单元测试框架也无法访问它。

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

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