XML与Wiremock的匹配

XML与Wiremock的匹配,xml,wiremock,Xml,Wiremock,我正在使用wiremock设置一个虚拟PHP服务器,并希望根据传递的一个XML字段进行匹配。我基本上会有多个请求进入同一个url,但它们之间的主要区别将是发票号码。我的wiremock JSON如下所示 { "request": { "method": "ANY", "urlPattern": ".*/test.php", "bodyPatterns" : [{ "equalToXml": "<InvoiceNumber>6</Invoi

我正在使用wiremock设置一个虚拟PHP服务器,并希望根据传递的一个XML字段进行匹配。我基本上会有多个请求进入同一个url,但它们之间的主要区别将是发票号码。我的wiremock JSON如下所示

{
  "request": {
    "method": "ANY",
    "urlPattern": ".*/test.php",
    "bodyPatterns" : [{
      "equalToXml": "<InvoiceNumber>6</InvoiceNumber>"
    }]
  },
  "response": {
    "status": 200,
    "bodyFileName": "sample.xml",
    "headers": {
      "Content-Type": "application/xml"
    }
  }
}
{
“请求”:{
“方法”:“任何”,
“urlPattern”:“*/test.php”,
“身体模式”:[{
“equalToXml”:“6”
}]
},
“答复”:{
“地位”:200,
“bodyFileName”:“sample.xml”,
“标题”:{
“内容类型”:“应用程序/xml”
}
}
}
当我使用Postman并且只传递带有
字段的XML时,这很好,但是当我添加第二个字段时,它就失败了


我希望能够将任何Xml传递给wiremock,只要它有
字段,它就会读取它

使用regex方法找到解决方案,并使用
matches
而不是
equalToXml

{
  "request": {
    "method": "ANY",
    "urlPattern": ".*/test.php",
    "bodyPatterns" : [{
      "matches": ".*<InvoiceNumber>6</InvoiceNumber>.*"
    }]
  },
  "response": {
    "status": 200,
    "bodyFileName": "sample.xml",
    "headers": {
      "Content-Type": "application/xml"
    }
  }
}
{
“请求”:{
“方法”:“任何”,
“urlPattern”:“*/test.php”,
“身体模式”:[{
“匹配项”:“*6.*”
}]
},
“答复”:{
“地位”:200,
“bodyFileName”:“sample.xml”,
“标题”:{
“内容类型”:“应用程序/xml”
}
}
}

您可能希望改用XPath匹配,如中所述。WireMock有一些很好的XML功能,包括占位符,值得保留

XPath

如果属性值为有效XML且与提供的XPath表达式匹配,则视为匹配。如果XPath求值返回任何元素,则认为XML文档匹配。WireMock委托给Java的内置XPath引擎(通过XMLUnit),因此它支持(至少)Java8的XPath版本1.0

Java:

.withRequestBody(matchingXPath("//InvoiceNumber[text()='6']"))
{   "request": {
    ...
     "bodyPatterns" : [ {
      "matchesXPath" : "//InvoiceNumber[text()='6']"
    } ]
    ...   },   ... }
JSON:

.withRequestBody(matchingXPath("//InvoiceNumber[text()='6']"))
{   "request": {
    ...
     "bodyPatterns" : [ {
      "matchesXPath" : "//InvoiceNumber[text()='6']"
    } ]
    ...   },   ... }