21

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

Community
  • 1
  • 1
fgysin
  • 11,329
  • 13
  • 61
  • 94
  • Does this answer your question? [delay MockWebServer response](https://stackoverflow.com/questions/26778379/delay-mockwebserver-response) – k4dima Jan 18 '21 at 00:09

3 Answers3

37

Try setting the response’s socket policy to NO_RESPONSE.

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • 3
    +1 Worked like a charm, **and** pointed me to the very useful SocketPolicy API which I somehow totally missed so far... – fgysin Sep 26 '16 at 13:59
  • I want to mock retrofit request so that timeout happens. Can i use this method? – Mahdi Feb 13 '19 at 15:26
  • 2
    When setting up the retrofit service, ensure that you've set your read timeout to something small so you don't end up with an unnecessary long running test. – oddmeter Feb 21 '19 at 15:30
  • This doesnt return a SocketTimeoutException. It returns "HTTP FAILED: java.io.IOException: unexpected end of stream" – DevinM Oct 22 '20 at 11:54
6

The setSocketPolicy() method is deprecated.

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

This will delay the MockWebServer response by 10 seconds.

Life Of Pai
  • 91
  • 1
  • 2
  • `setSocketPolicy()` is *un*-deprecated since okhttp 4.3: https://github.com/square/okhttp/blob/master/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt – Mr. AJ Nov 25 '22 at 18:52
0

To answer the original question, the following is what fgysin should try:

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