Loopj(AsyncHttpClient get方法)在Android Unit Test中没有返回响应

时间:2013-07-10 17:45:01

标签: android loopj

我正在尝试在Android项目上创建单元测试,该项目正在处理URL请求。我使用loopj库,但有些东西不起作用。我的清单中启用了Internet:

<uses-permission android:name="android.permission.INTERNET" />

测试方法中的Java代码:

    AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://www.yahoo.com", new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            System.out.println(response); // <------ I never get here!?!?!
        }
    });

Folowing程序(没有loopj)在相同的单元测试方法中工作:

    URL yahoo;
    yahoo = new URL("http://www.yahoo.com/");
    BufferedReader in;
    in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
        String inputLine;
    while ((inputLine = in.readLine()) != null) {
             System.out.println(inputLine);

            }
    in.close();

似乎loopj请求在单元测试类中不起作用,但它在基本Activity类中正常工作。有什么建议吗?

3 个答案:

答案 0 :(得分:5)

问题是因为loopj使用android.os.AsyncTask,它在单元测试环境中不起作用。

成功的关键是&#34; runTestOnUiThread&#34;方法。

public void testAsyncHttpClient() throws Throwable {
  final CountDownLatch signal = new CountDownLatch(1);
  final AsyncHttpClient httpClient = new AsyncHttpClient();
  final StringBuilder strBuilder = new StringBuilder();

  runTestOnUiThread(new Runnable() { // THIS IS THE KEY TO SUCCESS
    @Override
    public void run() {
      httpClient
          .get(
              "https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true",
              new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                  // Do not do assertions here or it will stop the whole testing upon failure
                  strBuilder.append(response);
                }

                public void onFinish() {
                  signal.countDown();
                }
              });
    }
  });

  try {
    signal.await(30, TimeUnit.SECONDS); // wait for callback
  } catch (InterruptedException e) {
    e.printStackTrace();
  }

  JSONObject jsonRes = new JSONObject(strBuilder.toString());
  try {
    // Test your jsonResult here
    assertEquals(6253282, jsonRes.getInt("id"));
  } catch (Exception e) {

  }

  assertEquals(0, signal.getCount());
}

Ful线程: https://github.com/loopj/android-async-http/issues/173

答案 1 :(得分:1)

小心你没有忘记在清单中声明网​​络访问,即

<manifest ....>
...
    <uses-permission android:name="android.permission.INTERNET" />
...
</manifest>

答案 2 :(得分:0)

基于Apache的HttpClient库构建的基于异步回调的Android Http客户端。所有请求都是在应用程序的主UI线程之外发出的,但任何回调逻辑都将在使用Android的Handler消息传递创建回调的同一线程上执行。

检查http://loopj.com/android-async-http/这可能对您有帮助!