我正在尝试在Android项目上创建单元测试,该项目正在处理URL请求.我使用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!?!?! } });
Folowing程序(没有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());}
Ful线程:
https://github.com/loopj/android-async-http/issues/173
以上是内存溢出为你收集整理的Loopj(AsyncHttpClient get方法)在Android Unit Test中没有返回响应全部内容,希望文章能够帮你解决Loopj(AsyncHttpClient get方法)在Android Unit Test中没有返回响应所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)