'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".



Solution 1:[1]

The setSocketPolicy() method is deprecated.

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

This will delay the MockWebServer response by 10 seconds.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Life Of Pai