okhttp icon indicating copy to clipboard operation
okhttp copied to clipboard

MockWebServer: setBodyDelay() doesn't work with empty body

Open akapuscinski-wr opened this issue 5 years ago • 4 comments

During tests I noticed that setBodyDelay() doesn't work for MockWebServer when response body is empty.

Try running following Kotlin snippet and send requests to http://localhost:8080. The first request will return immediately, the second one will wait 5 seconds as expected

fun main() {
    val mockWebServer = MockWebServer()
    mockWebServer.start(8080)

    mockWebServer.enqueue(MockResponse()
            .setBodyDelay(5, TimeUnit.SECONDS)
            .setResponseCode(200))
    mockWebServer.enqueue(MockResponse()
            .setBodyDelay(5, TimeUnit.SECONDS)
            .setBody("Anything") //body cannot be null otherwise delay doesn't work
            .setResponseCode(200))

    Thread.sleep(25 * 1000)
    mockWebServer.close()
}

akapuscinski-wr avatar Sep 24 '20 12:09 akapuscinski-wr

Unlikely there’s a simple fix for this. Instead, consider sending a 0-byte chunked body.

    mockWebServer.enqueue(MockResponse()
            .setBodyDelay(5, TimeUnit.SECONDS)
            .setChunkedBody("", 1)
            .setResponseCode(200))

swankjesse avatar Sep 25 '20 01:09 swankjesse

The current API is misleading. I would expect that @akapuscinski-wr 's example works. Thanks @swankjesse for your fix , however I would say it's rather a workaround.

rgonciarz avatar Sep 25 '20 07:09 rgonciarz

Would the correct behaviour be supporting body delay works for response codes requiring a body?

yschimke avatar Sep 25 '20 07:09 yschimke

Would the correct behaviour be supporting body delay works for response codes requiring a body?

I have the same problem, and I think you still need to support body delay works when the body is null. Because the client only knows that the current body is null when the delay time out. We can't think on the server side.

LitterSun avatar Nov 18 '20 10:11 LitterSun