How to assign responses in MockWebServer to expected requests?

membersound :

I want to create an integration test and mock a remote webservice as follows:

MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse()...);
server.enqueue(new MockResponse()...);
server.enqueue(new MockResponse()...);

Problem: I have a case where 3 requests are send in parallel to the remote. Thus, the order is always random.

Question: how can I tell MockWebServer to assign responses to expected requests?

Like pseudocode:

server.enqueue(new MockResponse()).forExpectedRequest(req1);
server.enqueue(new MockResponse()).forExpectedRequest(req2);
server.enqueue(new MockResponse()).forExpectedRequest(req3);

Is that possible?

Sneh :

From their documentation

By default MockWebServer uses a queue to specify a series of responses. Use a Dispatcher to handle requests using another policy. One natural policy is to dispatch on the request path. You can, for example, filter the request instead of using server.enqueue()

What you can do is this make changes in the code below.

final Dispatcher dispatcher = new Dispatcher() {

    @Override
    public MockResponse dispatch (RecordedRequest request) throws InterruptedException {

        switch (request.getPath()) {
            case "/v1/login/auth/":
                return new MockResponse().setResponseCode(200);
            case "v1/check/version/":
                return new MockResponse().setResponseCode(200).setBody("version=9");
            case "/v1/profile/info":
                return new MockResponse().setResponseCode(200).setBody("{\\\"info\\\":{\\\"name\":\"Lucas Albuquerque\",\"age\":\"21\",\"gender\":\"male\"}}");
        }
        return new MockResponse().setResponseCode(404);
    }
};
server.setDispatcher(dispatcher);

They use a switch statement on path but you can change it and implement your custom logic in here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324657&siteId=1