如何在Android单元测试中调试async-http

转自:https://github.com/loopj/android-async-http/issues/173

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());
}

猜你喜欢

转载自zyallday.iteye.com/blog/1949372
今日推荐