Android的HTTP测试与Robolectric测试、Android、HTTP、Robolectric

由网友(▍Fee1不止是一种感觉)分享简介:我有一个Android应用程序,其中应用程序的主要部分是APIcalls.java类,我发出HTTP请求来从服务器上的数据在应用程序中显示的数据。I have an Android app where the main part of the app is the APIcalls.java class where...

我有一个Android应用程序,其中应用程序的主要部分是APIcalls.java类,我发出HTTP请求来从服务器上的数据在应用程序中显示的数据。

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.

我想创建单元测试这个Java类,因为它是应用程序的大部分。这里是方法,用于从服务器获得数据:

I wanted to create unit test for this Java class since it's the most part of the app. 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;

我想我可以从这样的测试简单的API调用:

I thought I can make simple API calls from the tests like this:

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

但每次我做的一些测试HTTP调用,我得到一个错误:

But every time I make some http calls from the tests, I get an error:

Unexpected HTTP call GET

我知道我在这里做得不对,但任何人都可以告诉我,我该怎么正确地在Android中测试这个类?

I know I am doing something wrong here, but can anyone tell me how can I properly test this class in Android?

推荐答案

Robolectric提供了一些辅助方法来模拟对DefaultHttpClient HTTP响应。如果你使用DefaultHttpClient不使用这些方法,你会得到一个警告消息。

Robolectric provides some helper methods to mock http response for DefaultHttpClient. If you use DefaultHttpClient without using those methods, you would get a warning message.

下面是如何嘲笑HTTP响应的例子:

Here is an example of how to mock http response:

@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"));
    }
}

您可以通过查看 Robolectric的测试codeS 。

阅读全文

相关推荐

最新文章