我正在尝试在处理 URL 请求的 Android 项目上创建单元测试。我使用 loopj 库,但有些东西不起作用。我的 list 中启用了互联网:
<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!?!?!
}
});
以下过程(没有 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 类中正常工作。有什么建议吗?
最佳答案
问题是因为 loopj 使用 android.os.AsyncTask,它在单元测试环境中不起作用。
成功的关键是“runTestOnUiThread”方法。
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 - Loopj(AsyncHttpClient get 方法)在 Android 单元测试中不返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17577417/