user8778858
user8778858

Reputation: 51

How do I extract param from MockWebServer when testing?

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?

Upvotes: 5

Views: 3711

Answers (2)

Thomas Turrell-Croft
Thomas Turrell-Croft

Reputation: 742

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();
}

Upvotes: 2

Yuri Schimke
Yuri Schimke

Reputation: 13498

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();

Upvotes: 5

Related Questions