3

I am sending a request to a MockWebServer. I want to checkout parameters of said request for testing purposes. How can I extract it from MockWebServer?

2 Answers2

2

A good tutorial on MockWebServer https://www.baeldung.com/spring-mocking-webclient

You should be able to use getRequestUrl to access the full url including query params.

RecordedRequest recordedRequest = mockBackEnd.takeRequest();
 
assertEquals("GET", recordedRequest.getMethod());
assertEquals("/employee/100", recordedRequest.getPath());

HttpUrl requestUrl = recordedRequest.getRequestUrl();
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
  • for a particular query parameter, `recordedRequest.getRequestUrl().queryParameterValue("key");` – B.Z. Aug 30 '23 at 20:15
2

If you are using Spring you can use UriComponents.


@Test
void test() throws InterruptedException {

  mockWebServer.enqueue(new MockResponse().setStatus("HTTP/1.1 200 OK"));

  // Send HTTP request here

  MultiValueMap<String, String> queryParams = getQueryParams(mockWebServer.takeRequest());

  assertThat(queryParams.get("username"), is(List.of("another")));
}

// Test utility
private MultiValueMap<String, String> getQueryParams(RecordedRequest recordedRequest) {

  UriComponents uriComponents =
    UriComponentsBuilder.fromHttpUrl(recordedRequest.getRequestUrl().toString()).build();

  return uriComponents.getQueryParams();
}