Getting Robolectric to work with Volley

后端 未结 2 1233
我在风中等你
我在风中等你 2021-02-05 12:34

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

相关标签:
2条回答
  • 2021-02-05 12:57

    Inspired by @Thomas Moerman's answer, I created this class:

    public class RealRequestQueue {
    
        public static Builder newBuilder() {
            return new Builder();
        }
    
        public static final class Builder {
            private Cache mCache;
            private Network mNetwork;
    
            private Builder() {
            }
    
            public Builder cache(Cache val) {
                mCache = val;
                return this;
            }
    
            public Builder network(Network val) {
                mNetwork = val;
                return this;
            }
    
            public RequestQueue build() {
                if (mNetwork == null) mNetwork = new BasicNetwork(new HttpStack() {
                    @Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
                        return null;
                    }
                });
                if (mCache == null) {
                    Context context = RuntimeEnvironment.application.getApplicationContext();
                    mCache = new DiskBasedCache(new File(context.getCacheDir(), "volley"));
                }
    
                ResponseDelivery responseDelivery = new ExecutorDelivery(Executors.newSingleThreadExecutor());
                final RequestQueue queue = new RequestQueue(mCache, mNetwork, 4, responseDelivery);
    
                return queue;
            }
        }
    }
    

    I then spy on the request queue and inject it in to the system under test

    mQueue = spy(RealRequestQueue.newBuilder().network(mNetwork).build());
    
    0 讨论(0)
  • 2021-02-05 13:07

    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

    0 讨论(0)
提交回复
热议问题