让Robolectric与Volley合作

编程入门 行业动态 更新时间:2024-10-18 03:36:10
本文介绍了让Robolectric与Volley合作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试让Volley与Robolectric合作.我可以看到我的HTTP请求被调用,并且parseNetworkResponse被调用(我正在发送JsonRequest的自定义子类),但是我的监听器没有被调用.有什么建议吗?这是一个代码示例:

I am trying to get Volley working with Robolectric. I can see that my HTTP request is getting called, and parseNetworkResponse is getting called (I'm sending a custom subclass of JsonRequest), but my Listener is NOT getting called. Any advice? Here is a code sample:

@Test public void testTypeAheadClient() throws Exception { Robolectric.getFakeHttpLayer().interceptHttpRequests(false); //mRemoteRequestQueue and mCustomRequest are set up previously mRemoteRequestQueue.add(mCustomRequest); } private static class CustomRequest extends JsonRequest<MyObject> { public CustomRequest(String url, Response.Listener<MyObject> listener, Response.ErrorListener errorListener) { super(Request.Method.GET, url, null, listener, errorListener); } @Override protected Response<MyObject> parseNetworkResponse(NetworkResponse response) { System.out.println("in parseNetworkResponse"); try { MyObject myObject = new MyObject(new JSONArray(new String(response.data, "UTF-8"))); return Response.success(myObject, HttpHeaderParser.parseCacheHeaders(response)); } catch (Exception e) { e.printStackTrace(); return Response.error(new ParseError(e)); } } }

推荐答案

我通过将RequestQueue的ResponseDelivery替换为不使用Looper.getMainLooper()而是使用新的Executor的方法来解决了相同的问题.示例代码:

I solved that same problem by replacing the RequestQueue's ResponseDelivery with one that doesn't use the Looper.getMainLooper() but a new Executor. Example code:

public static RequestQueue newRequestQueueForTest(final Context context, final OkHttpClient okHttpClient) { final File cacheDir = new File(context.getCacheDir(), "volley"); final Network network = new BasicNetwork(new OkHttpStack(okHttpClient)); final ResponseDelivery responseDelivery = new ExecutorDelivery(Executors.newSingleThreadExecutor()); final RequestQueue queue = new RequestQueue( new DiskBasedCache(cacheDir), network, 4, responseDelivery); queue.start(); return queue; }

注意:使用Robolectric-2.2-SNAPSHOT,以前的版本在Volley上不能很好地发挥作用.

Note: use Robolectric-2.2-SNAPSHOT, the previous version doesn't play well with Volley.

希望这会有所帮助

更多推荐

让Robolectric与Volley合作

本文发布于:2023-11-12 20:06:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Robolectric   Volley

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!