我正试图在处理URL请求的Android项目上创建单元测试。我使用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!?!?!
}
});
折叠程序(无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());
}
富尔螺纹:https://github.com/loopj/android-async-http/issues/173
注意不要忘记在清单中声明网络访问,即
<manifest ....>
...
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
一个基于异步回调的安卓Http客户端,构建在Apache的HttpClient库之上。所有请求都是在应用程序的主UI线程之外发出的,但任何回调逻辑都将在使用Android的Handler消息传递创建回调的同一线程上执行。
检查http://loopj.com/android-async-http/这可能会对你有所帮助!