在 Wiremock 中计算 XPath 表达式



我正在使用Wiremock进行测试,我遇到了以下问题。

有 2 种情况

  1. 请求何时出现,如下所示
<Body>
<ElementA>Element A</ElementA>
<ElementB>123<ElementB>
</Body>

在这里,我们只需要检查元素 B 的值是否应为 123。

  1. 当请求如下所示
<Body>
<ElementA flag="true">Element A</ElementA>
<ElementB>123<ElementB>
</Body>

在这里,我们需要检查元素 B 的值是否应为 123,标志的值也应为 true。

现在我希望我的 wiremock在这两种情况下都返回不同的响应,我的 wiremock 配置文件看起来像这样。

  1. 对于案例 1
{
"request": {
"url": "/",
"method": "POST",
"bodyPatterns": [
{
"matchesXPath": {
"expression": "//ElementB/text()",
"contains": "123"
}
},{
"absent": {
"expression":  "//ElementA[@flag=true]"
}
}
]
},
"response": {
"status": 200,
"bodyFileName": "someFile.xml",
"headers": {
"Content-Type": "text/xml; charset=utf-8"
}
}
}

但在这里,它只把缺席当作真实,而另一个元素不会来。 来自wiremock的示例:

"bodyPatterns" : [ {
"matchesXPath" : {
"expression" : "//ElementA/text()",
"contains" : "123"
}
}, {
"absent" : true
} ]
  1. 对于情况 2
{
"request": {
"url": "/",
"method": "POST",
"bodyPatterns": [
{
"matchesXPath": {
"expression": "//ElementB[text()='123']"
},
"matchesXPath": {
"expression": "//ElementA[@flag]",
"contains": "true"
}
}
]
},
"response": {
"status": 200,
"bodyFileName": "someotherFile.xml",
"headers": {
"Content-Type": "text/xml; charset=utf-8"
}
}
}

但不知何故,它无法在情况 1 中返回响应,而在情况 2 中,它不关心第一个条件,它只检查 flag 的值是否为真。

任何帮助/指示将不胜感激。

我不相信你需要absent标志。我认为您可以使用优先级来强制 WireMock 在转向更一般的响应之前检查更具体的请求。

我还认为您在案例 2 中检查 XPath 的方式存在错误。我会尝试类似的东西...

{
"priority": 1,
"request": {
"url": "/",
"method": "POST",
"bodyPatterns": [
{
"matchesXPath": {
"expression": "//ElementB[text()]",
"contains": "123"
},
"matchesXPath": {
"expression": "//ElementA[@flag]",
"contains": "true"
}
}
]
},
"response": {
"status": 200,
"bodyFileName": "someFile.xml",
"headers": {
"Content-Type": "text/xml; charset=utf-8"
}
}
}

看看"priority": 1的添加.我还认为,如果您不需要它们与正则表达式模式匹配,则可以更改matchesXPath对象以简单地检查值。"matchesXPath": "//ElementB[text() = 123]"

{
"priority": 2,
"request": {
"url": "/",
"method": "POST",
"bodyPatterns": [
{
"matchesXPath": {
"expression": "//ElementB[text()]",
"contains": "123"
}
}
]
},
"response": {
"status": 200,
"bodyFileName": "someotherFile.xml",
"headers": {
"Content-Type": "text/xml; charset=utf-8"
}
}
}

因为优先级 1 映射检查flag=true,所以优先级 2 映射上的匹配项不包含具有 flag=true 属性的元素 A。因此,在 WireMock 检查优先级 1 映射(这需要flag=true匹配(之后,它会检查优先级 2 映射(这只需要 ElementB 的文本 = 123(。

最新更新