Unit Testing A Network Response. Works When Debugging, Not When Actually Running
Solution 1:
Volley relies on Looper.getMainLooper() to handle its executions. When using a RobolectricTestRunner, Robolectric mocks this out and as such it will not be correctly set up, thus resulting in a failed test.
In my specific case, when I was using breakpoints, the system actually does set up the main looper, because the system is utilizing it to show the breakpoints / debugging tools. This thus describes the reasoning behind the behaviour found in my initial question.
Now for a solution as to getting real network responses with Volley during a unit test, the executor must be changed to not be using the main looper.
As an easy solution, create a request queue that relies on Executor.singleThreadExecutor() instead of the Main Looper.
Here is what I mean:
//Specific test queue that uses a singleThreadExecutor instead of the mainLooper for testing purposes.public RequestQueue newVolleyRequestQueueForTest(final Context context) {
FilecacheDir=newFile(context.getCacheDir(), "cache/volley");
Networknetwork=newBasicNetwork(newHurlStack());
ResponseDeliveryresponseDelivery=newExecutorDelivery(Executors.newSingleThreadExecutor());
RequestQueuequeue=newRequestQueue(newDiskBasedCache(cacheDir), network, 4, responseDelivery);
queue.start();
return queue;
}
Then, use that as your request queue for Volley during the tests.
The key here is:
ResponseDelivery responseDelivery = new ExecutorDelivery(Executors.newSingleThreadExecutor());
Hope this helps!
Post a Comment for "Unit Testing A Network Response. Works When Debugging, Not When Actually Running"