Capturing HTTP Requests with okhttp's MockWebServer.takeRequest

Featured image for sharing metadata for article

I came across okhttp's MockWebServer as part of Integration Testing Your Spring WebClients with okhttp's MockWebServer, and wanted to verify that HTTP requests made by my HTTP clients were well-formed.

To do this, there's the takeRequest method, which on my first read, I expected to need to be called at the same time as the HTTP request was outgoing.

It turns out that the way to do this, is instead to call it after an HTTP request is sent, using it purely for verification means:

@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");
}

Note the need for enqueueing a MockResponse, as without it the tests will fail.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.