Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Robolectric to work with Volley

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));
        }
    }
}
like image 887
adevine Avatar asked May 29 '13 14:05

adevine


1 Answers

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;
}

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

Hope this helps

like image 91
Thomas Moerman Avatar answered Oct 20 '22 10:10

Thomas Moerman