我正在尝试模拟在POST中接受JSON正文的API调用,它有两个可能的响应:
SearchCenter
属性,请回答ASearchCenter
,则回答B在Wiremock文档的“请求匹配”一章中,它仅显示如何正面匹配JSON,没有显示如何匹配缺少的属性。
样品要求SearchCenter
:
{
"GeoCoordinatesResponseFormat": "DecimalDegree",
"ProviderID": "bla bla",
"SearchCenter": {
"GeoCoordinates": {
"DecimalDegree": {
"Latitude": "{{search_lat}}",
"Longitude": "{{search_lon}}"
}
},
"Radius": {{search_radius}}
}
}
不提供样品要求SearchCenter
:
{
"GeoCoordinatesResponseFormat": "DecimalDegree",
"ProviderID": "bla bla"
}
编辑:我可能已经超越了自己-我认为有一个更简单的匹配解决方案。您可以对regex使用负匹配。(负前瞻)我仍然认为我更喜欢优先级方法。
stubFor(any(urlPathEqualTo("/some-endpoint"))
.withRequestBody(matchingJsonPath("$.?!SearchCenter"))
.willReturn(ok("Body does not contain Search Center"));
stubFor(any(urlPathEqualTo("/some-endpoint"))
.withRequestBody(matchingJsonPath("$.SearchCenter"))
.willReturn(ok("Body does contain Search Center"));
有两种方法可以完成此操作。第一个将使用正则表达式匹配器/不匹配器。假设您正在使用存根...
stubFor(any(urlPathEqualTo("/some-endpoint"))
.withRequestBody(notMatching("\"SearchCenter\": \{ .* \}"))
.willReturn(ok("Body does not contain Search Center"));
stubFor(any(urlPathEqualTo("/some-endpoint"))
.withRequestBody(matchingJsonPath("$.SearchCenter"))
.willReturn(ok("Body does contain Search Center"));
这会在不匹配时进行正则表达式匹配,以检查该字段是否不存在,然后检查该字段确实存在的情况下的JSON路径匹配。(我没有测试实际的代码,因此正则表达式匹配/ JSON路径可能需要进行一些调整。)
但是,我认为更好的解决方案是让更具体的匹配返回一个响应,而不太具体的匹配返回另一个响应。我们可以通过优先事项实现这一目标。
stubFor(any(urlPathEqualTo("/some-endpoint"))
.atPriority(1)
.withRequestBody(matchingJsonPath("$.SearchCenter"))
.willReturn(ok("Body does contain Search Center"));
stubFor(any(urlPathEqualTo("/some-endpoint"))
.atPriority(2)
.willReturn(ok("Body does not contain Search Center"));
可在此处找到有关优先级的信息。优先级上的tl; dr强制WireMock先检查某些匹配项,然后再检查其他匹配项。在这种情况下,我们将检查请求正文是否包含所需的字段(“搜索中心”),如果包含,则返回匹配项。如果我们有其他具有相同优先级的存根(1),则在移至下一个优先级之前也会对它们进行检查。如果找不到我们要匹配的字段,我们将移至下一个优先级。由于优先级2的存根不需要与请求正文中的JSON路径匹配,因此我们将进行匹配。
我偏好优先于特定匹配两次的原因仅仅是因为我喜欢具有通用存根提供的“后备”行为,其中对“ / some-endpoint”的任何调用都将通过通用响应来实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句