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.
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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.