如何在Android单元测试中调试async-http
16lz
2021-01-23
阅读更多 转自: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());
}
更多相关文章
- andorid RecyclerView下拉刷新,上拉加载更多
- OpenGL ES教程V之更多3D模型(原文对照)
- Android从零撸美团(四) - 美团首页布局解析及实现 - Banner+自定
- EditText设置更多文字为省略号
- 短视频PHP源码Android 打造专属的下拉刷新 加载更多
- Android 1.6 支持更多的屏幕大小和分辨率
- NestedScrollView+RecyclerView滑动冲突问题,加载更多
- Activity生命周期的回调,你应该知道得更多!--Android源码剖析(上)
- Android中文文档v0.1 beta低调发布,期待更多同学来参加review