如何在Android单元测试中调试async-http
16lz
2022-04-19
阅读更多 转自: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());
}
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());
}
更多相关文章
- 阅读《Android(安卓)从入门到精通》(14)——时间选择器
- android 三种定位方式 设计思路
- android apk dex odex jar 等文件的 反编译工具
- Android(安卓)Message源码阅读
- 25个你应该阅读的Android网站
- android 音频系统java部分代码阅读
- 25个你应该阅读的Android网站
- 阅读《Android(安卓)从入门到精通》(7)——图片按钮
- 阅读《Android(安卓)从入门到精通》(2)——熟悉开发环境