You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WireMock中验证针对同一URL但携带不同请求体的两次POST请求?

Fixing WireMock's Verification for Two Distinct POST Requests to the Same URL

Got it, let's sort out this WireMock verification issue! The problem with your current code is that while you're calling verify() twice, WireMock's default behavior for an unqualified verify() is to check if the request occurred at least once—but this doesn't enforce that both distinct request bodies were sent exactly once. Worse, if your test setup only ends up sending the second request, the first verify() would fail, but it might feel like WireMock is only "validating the last line" because you're focusing on the passing check. Let's fix this properly.

Solution 1: Explicitly Verify Each Request Occurs Exactly Once

Add a count parameter to each verify() call to ensure WireMock checks that each request body was used exactly once for the /my-url endpoint:

// Verify first request body was sent once
verify(1, postRequestedFor(urlEqualTo("/my-url"))
    .withRequestBody(equalToJson(resourceAsString("my-first-body.json"), true, false)));

// Verify second request body was sent once
verify(1, postRequestedFor(urlEqualTo("/my-url"))
    .withRequestBody(equalToJson(resourceAsString("my-other-body.json"), true, false)));

The 1 as the first argument tells WireMock to confirm the matching request happened exactly once. This works regardless of the order the requests were sent in.

Solution 2: Verify Request Order (If Sequence Matters)

If your test requires that the first request body is sent before the second, use verifySequence() instead. This ensures WireMock checks the requests arrived in the exact order you specify:

verifySequence(
    postRequestedFor(urlEqualTo("/my-url"))
        .withRequestBody(equalToJson(resourceAsString("my-first-body.json"), true, false)),
    postRequestedFor(urlEqualTo("/my-url"))
        .withRequestBody(equalToJson(resourceAsString("my-other-body.json"), true, false))
);

This method automatically verifies each request occurred once in the given sequence.

Why Your Original Code Didn't Work As Expected

Without the count parameter, verify() defaults to checking for at least one occurrence of the request. So if your test accidentally sent the second request twice, the first verify() would fail (since the first body was never sent), but if you only noticed the second check passing, it might feel like WireMock is ignoring the first line. By adding the explicit count or using verifySequence, you make the validation precise and ensure both requests are accounted for.

内容的提问来源于stack exchange,提问作者Swoot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:42:30