Search code examples
javaspring-bootmockingwiremockstubbing

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.


Solution

  • 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.