14

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.

JJD
  • 50,076
  • 60
  • 203
  • 339
Mag Hakobyan
  • 510
  • 1
  • 4
  • 17

1 Answers1

22

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);
JJD
  • 50,076
  • 60
  • 203
  • 339
Mag Hakobyan
  • 510
  • 1
  • 4
  • 17
  • 1
    Can you assign a different dispatcher for each test? – paxcow Dec 23 '20 at 15:10
  • Each server has one dispatcher.So if you want to have many dispatchers you have to create many servers,which is not optimal.So you shall find a way to handle many responses in one dispatcher. – Mag Hakobyan Dec 24 '20 at 07:27
  • 1
    While it will most likely be possible to find a way to handle all tests in one dispatcher another approach could be to instantiate and close the mockwebserver in BeforeEach instead of BeforeAll. So you have one server per test and can setDispatcher individually. – Jens Jul 17 '21 at 11:45
  • 1
    you saved my day – pvpkiran Jun 05 '23 at 09:00