使用Robolectric进行Android http测试

11 android robolectric android-testing

我有一个Android应用程序,其中应用程序的主要部分是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;
Run Code Online (Sandbox Code Playgroud)

我以为我可以通过这样的测试进行简单的API调用:

api.get("www.example.com")
Run Code Online (Sandbox Code Playgroud)

但是每次我从测试中调用一些http调用时,都会出错:

Unexpected HTTP call GET
Run Code Online (Sandbox Code Playgroud)

我知道我在这里做错了什么,但有谁能告诉我如何在Android中正确测试这个类?

小智 23

谢谢你的所有答案,但我找到了我想要的东西.我想测试真正的HTTP调用.

通过添加Robolectric.getFakeHttpLayer().interceptHttpRequests(false); 你告诉Robolectric不要拦截这些请求,它允许你进行真正的HTTP调用

  • @Gem使用最新版本的Robolectric 3.0,将其添加到build.gradle`testCompile'org.robolectric:shadows-httpclient:3.0'`然后你可以使用:FakeHttp.getFakeHttpLayer().interceptHttpRequests(false); (6认同)

Pol*_*oly 7

Robolectric提供了一些帮助方法来模拟DefaultHttpClient的http响应.如果在不使用这些方法的情况下使用DefaultHttpClient,则会收到警告消息.

以下是如何模拟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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过查看Robolectric的测试代码找到更多示例.