michalbrz
michalbrz

Reputation: 3504

How to set default response for MockWebServer?

MockWebServer is awesome library, but there is one thing that is surprisingly hard to do: set default response.

To be specific: I want to have ability to set response that is returned if no response was specified using server.enqueue(response).

I would like to be able to do something like:

server.setDefaultResponse(okResponse)
server.enqueue(customResponse)

And then when my tests call server twice (or more), every response after the first one would be okResponse.

When tests get more complicated and multiple calls to server are needed, sometimes specifying every single response (often simple 200 OK) is tedious and pollutes tests.

Is there any simpler way to do this than creating your own Dispatcher? Creating it properly (with support for multiple responses) sounds like overkill for such a small thing.

Upvotes: 2

Views: 1835

Answers (1)

michalbrz
michalbrz

Reputation: 3504

There is improvement that can be done in comparison to implementing your own Dispatcher. When looking at MockWebServer implementation I found that its default dispatcher is QueueDispatcher.

And it has some very handy methods, like:

public void setFailFast(boolean failFast)

public void setFailFast(MockResponse failFastResponse)

setFailFast(true) sets server to "fail fast" mode i.e. if no response in enqueued, it doesn't wait, just returns HTTP 404 response immediately.

setFailFast(okResponse) sets response to return in "fail fast" mode, which exactly answers this question.

The problem is, you don't have direct access to dispatcher field in MockWebServer, so what you need to do is set your own instance of QueueDispatcher and then set default response (or "fail fast" response) on it, like that:

val dispatcher = QueueDispatcher()
dispatcher.setFailFast(okResponse)
server.setDispatcher(dispatcher)

Upvotes: 2

Related Questions