Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockWebServer response delay - testing timeouts

I'm trying to test HTTP timeout scenarios using a MockWebServer which answers my test requests sent with Retrofit/OkHttp. (This question was asked before some years ago, but at the time concerned a bug in the MockWebServer. Also, the API has since changed a fair bit, so I think reposting this question is warranted.)

There seem to be several related methods, but I'd appreciate a solution to this issue with a clear example: I'm unsure about the difference between..

  • .delayBody and
  • .throttleBody

Also, both of these methods seem to only delay/throttle the body - is it not possible to set a timeout for the response header? I.e. something along the lines of "wait X seconds after the next incoming request before you send out any response".

like image 821
fgysin Avatar asked Sep 22 '16 12:09

fgysin


People also ask

How MockWebServer works?

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.

What is MockWebServer enqueue?

enqueue(MockResponse response) Scripts response to be returned to a request made in sequence. Dispatcher. getDispatcher() Returns the dispatcher used to respond to HTTP requests.


2 Answers

Try setting the response’s socket policy to NO_RESPONSE.

like image 167
Jesse Wilson Avatar answered Oct 20 '22 22:10

Jesse Wilson


The setSocketPolicy() method is deprecated.

MockResponse mockResponse = new MockResponse().setBodyDelay(10, TimeUnit.SECONDS);

This will delay the MockWebServer response by 10 seconds.

like image 3
Life Of Pai Avatar answered Oct 21 '22 00:10

Life Of Pai