Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign responses in MockWebServer to expected requests?

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?

like image 711
membersound Avatar asked Aug 15 '19 12:08

membersound


1 Answers

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.

like image 184
Sneh Avatar answered Oct 16 '22 22:10

Sneh