简体   繁体   中英

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

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM