如何用WireMock MappingBuilder匹配请求体中值为null的JSONPath?
WireMock匹配JSON字段为null的Java代码解决方法
要生成目标中的WireMock请求映射,直接使用matchingJsonPath("cursor", equalTo(null))会触发NullPointerException,因为equalTo()方法不允许传入null参数。可以通过以下两种方式解决:
方法一:在JSON Path表达式中直接判断null
直接在JSON Path表达式里写判断逻辑,无需额外的匹配器参数:
import static com.github.tomakehurst.wiremock.client.WireMock.*; // 构建请求映射 stubFor(post(urlPattern("/kziwynya/ep1")) .withRequestBody(matchingJsonPath("cursor == null")));
这种方式生成的请求映射JSON会和你预期的一致,JSON Path表达式cursor == null会精准匹配cursor字段值为null的请求体。
方法二:使用nullValue()匹配器
如果你的WireMock版本(一般2.x及以上)支持nullValue()匹配器,可以用这种更清晰的写法:
import static com.github.tomakehurst.wiremock.client.WireMock.*; // 构建请求映射 stubFor(post(urlPattern("/kziwynya/ep1")) .withRequestBody(matchingJsonPath("cursor", nullValue())));
nullValue()是WireMock提供的专门匹配null值的内置匹配器,不会触发空指针异常,同样能生成符合要求的请求映射。
内容的提问来源于stack exchange,提问作者Nikunj Aggarwal
相关产品推荐
相关产品推荐

