How to capture the body of a request that was stubbed with Wiremock

4.9k Views Asked by At

Is there a way to capture the body of a post request that was stubbed with wiremock? I'm looking for something similar to Mockito's ArgumentCaptor.

I have the following stub:

stubFor(post(urlPathEqualTo(getUploadEndpoint())).willReturn(().withStatus(HttpStatus.OK.value())));

I want to be able to see how the actual request was performed, get its body and assert it.

I have tried by using .withRequestBody(equalToXml(...)) in the stub, since the body is the String representation of an XML. This does not work for me, because equalToXml is too strict, not allowing free text without surrounding tags for example.

4

There are 4 best solutions below

0
Gabriela83 On BEST ANSWER

I managed to find a solution by doing this: I attributed a UUID to the stub

stubFor(post(urlPathEqualTo(getUploadEndpoint())).willReturn(aResponse().withStatus(HttpStatus.OK.value()))).withId(java.util.UUID.fromString(UUID)));

and I gathered all serve events happening on this particular endpoint

List<ServeEvent> allServeEvents = getAllServeEvents(ServeEventQuery.forStubMapping(java.util.UUID.fromString(UUID)));
// this list should contain one stub only
assertThat(allServeEvents).hasSize(1);
ServeEvent request = allServeEvents.get(0);
String body = request .getRequest().getBodyAsString();

Then I used XMLUnit to assert this body. Seems to do the job, but I'm open to any other solutions if available.

1
Robert Elliot On

You can use the API to verify that a request was made with the expected body.

import static com.github.tomakehurst.wiremock.client.WireMock.*

verify(
    postRequestedFor(urlEqualTo(getUploadEndpoint()))
        .withRequestBody(matchingXPath("your xpath here"))
);

See WireMock / Request Matching / XPath for examples of XPath matching.

0
Robert Elliot On

Alternatively, you can use the API to find requests that match a predicate:

import static com.github.tomakehurst.wiremock.client.WireMock.*;

List<LoggedRequest> requests = findAll(
    postRequestedFor(urlEqualTo(getUploadEndpoint()))
        .withRequestBody(matchingXPath("your xpath here"))
);

Then you can assert whatever you want about the matched requests.

0
Vijay Kesanupalli On

I tried like below

return stubFor(post(uri)
                .withHeader("Content-Type", equalTo("application/json"))
                .withHeader("Accept", equalTo("application/json"))
                .withRequestBody(WireMock.equalToJson(requestPayload))
                .willReturn(WireMock.aResponse()
                        .withStatus(HttpStatus.OK.value())
                        .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
                        .withBody(response))).toString();