java 如何捕获使用Wiremock存根的请求主体

mzmfm0qo  于 2023-01-19  发布在  Java
关注(0)|答案(3)|浏览(113)

有没有办法捕获用wirerock存根的post请求的主体?我正在寻找类似于Mockito的ArgumentCaptor的东西。
我有以下存根:

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

我希望能够看到实际的请求是如何执行的,获得它的主体并Assert它。
我尝试在存根中使用.withRequestBody(equalToXml(...)),因为主体是XML的String表示,但这对我不起作用,因为equalToXml太严格了,例如不允许没有周围标记的自由文本。

whitzsjs

whitzsjs1#

我设法通过这样做找到了解决方案:我给存根赋予了UUID

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

我收集了这个端点上发生的所有服务器事件

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

然后我使用XMLUnit来Assert这个主体。看起来可以完成这项工作,但如果有其他解决方案,我也会考虑。

cbjzeqam

cbjzeqam2#

或者,您可以使用API查找与 predicate 匹配的请求:

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

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

然后,您可以Assert关于匹配请求的任何内容。

w7t8yxp5

w7t8yxp53#

您可以使用该API执行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"))
);

有关XPath匹配的示例,请参见WireMock /请求匹配/ XPath。

相关问题