Add timeout to MockWebServer so that it does not hang server.takeRequest(1, TimeUnit.SECONDS);
Answer from Prayag on Stack Overflow Top answer 1 of 3
5
Add timeout to MockWebServer so that it does not hang server.takeRequest(1, TimeUnit.SECONDS);
2 of 3
2
There seems to be a problem with MockWebServer's dispatch queue, which freezes for some reason when serving responses which are not 200 or 302. I have solved this by providing a custom dispatcher:
MockWebServer server = ...;
final MockResponse response = new MockResponse().setResponseCode(401);
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request)
throws InterruptedException {
return response; // this could have been more sophisticated
}
});
Tested with MockWebServer 2.0.0
Jamie Tanna
jvt.me › posts › 2022 › 02 › 07 › okhttp-mockwebserver-takerequest
Capturing HTTP Requests with okhttp's `MockWebServer.takeRequest` · Jamie Tanna | Software Engineer
February 7, 2022 - @Test void test() throws InterruptedException { MockWebServer server = new MockWebServer(); // required to be set, otherwise `takeRequest` will never return anything server.enqueue(new MockResponse()); RestAssured.given().get(server.url("/products").toString()); RecordedRequest request = server.takeRequest(1, TimeUnit.SECONDS); assertThat(request).isNotNull(); assertThat(request.getPath()).isEqualTo("/products"); }
Industrial Logic
industriallogic.com › blog › better-integration-testing-with-mockwebserver
Better Integration Testing with MockWebServer
April 13, 2022 - Adding this timeout for all your mockServer.takeRequest() methods is a good idea so the tests will fail fast when they fail, instead of hanging. private void assertBackendServerWasCalledCorrectlyForPOST(RecordedRequest recordedRequest) { assertThat(recordedRequest).as("Request did not reach MockWebServer").isNotNull(); assertThat(recordedRequest.getMethod()).isEqualTo("POST"); String expectedRequestBody = "[text={\"year\":1972,\"month\":10,\"day\":10,\"hour\":10,\"message\":\"Hi\"}]"; assertThat(recordedRequest.getBody().readByteString().toString()).isEqualTo(expectedRequestBody); } Getting the body from the request to the backend can be done by reading the byte string of the body and converting it to a string.
Google
android.googlesource.com › platform › external › okhttp › + › refs › heads › oreo-m2-s4-release › mockwebserver › README.md
MockWebServer
RecordedRequest request = server.takeRequest(); assertEquals("POST /v1/chat/send HTTP/1.1", request.getRequestLine()); assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); assertEquals("{}", request.getUtf8Body()); By default MockWebServer uses a queue to specify a series of responses.
Program Creek
programcreek.com › java-api-examples
okhttp3.mockwebserver.MockWebServer#takeRequest
@Test public void have_correct_retrofit_request_format() throws IOException, InterruptedException { MockWebServer mockWebServer = new MockWebServer(); mockWebServer.start(); mockWebServer.enqueue(new MockResponse()); TestService testService = testService(mockWebServer); testService.test(Fields.<String>builder() .fields( Field.<String, String>create("property_one"), Field.<String, String>create("property_two"), NestedField.<String, String>create("nested_property").with( Field.<String, String>create("nested_property_one"))) .build()) .execute(); RecordedRequest recordedRequest = mockWebServer.takeRequest(); assertThat(recordedRequest.getPath()).isEqualTo( "/api/?fields=property_one,property_two,nested_property[nested_property_one]"); mockWebServer.shutdown(); }
Okio
square.github.io › okhttp › 3.x › mockwebserver › okhttp3 › mockwebserver › MockWebServer.html
MockWebServer (MockWebServer 3.14.0 API)
public RecordedRequest takeRequest() throws InterruptedException
Okio
square.github.io › okhttp › 5.x › mockwebserver3 › mockwebserver3 › -mock-web-server › take-request.html
takeRequest
mockwebserver3/mockwebserver3/MockWebServer/takeRequest · fun takeRequest(): RecordedRequest · Awaits the next HTTP request, removes it, and returns it. Callers should use this to verify the request was sent as intended. This method will block until the request is available, possibly forever.
Stack Overflow
stackoverflow.com › questions › 64433020 › mockwebserver-takerequest-method-infinite-execution
android - Mockwebserver takeRequest() method infinite execution - Stack Overflow
I added a request using enque (), but using the debugger, you can see that when you call takeRequest inside it, requestQueue = 0, which means that there is no request, after which takeRequest () waits for a request indefinitely. What could be the problem? class ExampleUnitTest { private lateinit var mockWebServer: MockWebServer @Before fun setup() { mockWebServer = MockWebServer() mockWebServer.start() mockWebServer.url("/") } @After fun teardown() { mockWebServer.shutdown() } @Test fun `test`(){ val response = MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .setBody("response body") mockWebServer.enqueue(response) var recordedRequest = mockWebServer.takeRequest() ...
GitHub
github.com › square › okhttp › issues › 5208
MockWebServer takeRequest with timeout should be nullable · Issue #5208 · square/okhttp
June 20, 2019 - MockWebServer takeRequest() with timeout function signature is NotNull: fun takeRequest(timeout: Long, unit: TimeUnit): RecordedRequest = requestQueue.poll(timeout, unit) However the underlying LinkedBlockingQueue poll() returns nulls on timeout, causing an IllegalStateException when a NotNull kotlin function tries to return null.
Author: square
Stevenschwenke
stevenschwenke.de › testingJavaHttpClientsWithMockWebServer
Testing Java HTTP Clients with MockWebServer
July 18, 2022 - @Test void retrievingTokenShouldSendPostRequest() throws InterruptedException { // Mock response mockBackend.enqueue(new MockResponse() .setBody("{\"value\":\"test\"}") .addHeader("Content-Type", "application/json")); // Execute request to locally running mock web server myService.getToken(); // Validate request was send as expected RecordedRequest recordedRequest = mockBackend.takeRequest(); assertEquals("POST", recordedRequest.getMethod()); }
How to do in Java
howtodoinjava.com › home › java libraries › getting started with mockwebserver and junit
Getting Started with MockWebServer and JUnit
July 11, 2022 - We can use RecordedRequest instance to fetch the details of HTTP requests MockWebServer to make sure our WebClient sent it correctly. RecordedRequest request = server.takeRequest(); assertEquals("/api-url-two", request.getPath()); assertEquals("POST", request.getMethod()); assertNotNull(request.getHeader("Authorization")); assertEquals("<data />", request.getBody().readUtf8()); In this tutorial, we learned to use MockWebServer to mock APIs and responses and later consume these API using WebClient.
Shouldn't Be Hard
arhohuttunen.com › spring-boot-webclient-mockwebserver
Testing Spring Boot WebClient With MockWebServer | Shouldn't Be Hard
May 22, 2021 - To verify that we used the correct HTTP method and URL in our request, we can ask MockWebServer to retrieve the last request. Calling the takeRequest() method returns a RecordedRequest, which holds the HTTP method, URL, path, headers, and request body.
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Okio
square.github.io › okhttp › 3.x › mockwebserver › index.html
Overview (MockWebServer 3.14.0 API)
JavaScript is disabled on your browser · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version
rieckpil
rieckpil.de › home › spring framework tutorials › test spring webclient with mockwebserver from okhttp
Test Spring WebClient with MockWebServer from OkHttp - rieckpil
August 27, 2021 - With this elegant solution, you can easily test parts of your application that use the RestTemplate and mock HTTP responses. Unfortunately, this test setup does not work for the Spring WebClient. It seems there won’t be an integration with the MockRestServiceServer for the WebClient. The recommended way is to use MockWebServer from OkHttp.
DeepWiki
deepwiki.com › square › okhttp › 3.2-mockwebserver
MockWebServer | square/okhttp | DeepWiki
July 3, 2025 - When a client makes a request to MockWebServer: The server records all details of the incoming request · It forwards the request to its configured dispatcher · The dispatcher determines which response to return · The server applies any socket policies to simulate network conditions · The response is sent back to the client · The recorded request is stored and can be accessed via takeRequest() Sources: mockwebserver/README.md:31-75 ·