Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test with consecutive calls to MockWebServer

I am writing test for an Activity which makes several consecutive calls to server. My MockWebServer mixes sequence of responses.e.g. When I make two consecutive requests request1 and request2 it sometimes returns request2's Json in response to request1 and request1's Json in response to request2. How can I specify which response MockWebServer has to return to specified request?

server.enqueue(new MockResponse()
                .setResponseCode(200)
                .setBody(readFromFile("response1 path"));

server.enqueue(new MockResponse()
                .setResponseCode(200)
                .setBody(readFromFile("response2 path"));

In documentation it is said "Enqueue scripts response to be returned to a request made in sequence. The first request is served by the first enqueued response; the second request by the second enqueued response; and so on."

This sequence doesn't work in case of parallel requests.

like image 473
Mag Hakobyan Avatar asked Jan 31 '19 10:01

Mag Hakobyan


1 Answers

To handle the sequence of responses I have written a dispatcher for my MockServer instance. It receives a request, checks it's URL's endpoint and returns corresponding response

Dispatcher mDispatcher = new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) {
         if (request.getPath().contains("/request1")) {
             return new MockResponse().setBody("reponse1");
         }
         if (request.getPath().contains("/request2")) {
             return new MockResponse().setBody("reponse2");
         }
         return new MockResponse().setResponseCode(404);
       }
     }
 mMockServer.setDispatcher(mDispatcher);
like image 123
Mag Hakobyan Avatar answered Oct 10 '22 05:10

Mag Hakobyan