XML与Wiremock匹配

时间:2019-06-21 20:22:03

标签: xml wiremock

我正在使用Wiremock设置一个虚拟PHP服务器,并希望根据传递的XML字段之一进行匹配。我基本上会在同一个网址中收到多个请求,但它们之间的主要区别是发票号。我的Wiremock JSON看起来像这样

vb_

当我使用Postman并且仅通过带有{ "request": { "method": "ANY", "urlPattern": ".*/test.php", "bodyPatterns" : [{ "equalToXml": "<InvoiceNumber>6</InvoiceNumber>" }] }, "response": { "status": 200, "bodyFileName": "sample.xml", "headers": { "Content-Type": "application/xml" } } } 字段的XML时,这种方法很好用,但是当我添加第二个字段时,它失败了。

我希望能够将任何Xml传递给Wiremock,只要它具有<InvoiceNumber></InvoiceNumber>字段,它将读取它。

2 个答案:

答案 0 :(得分:1)

使用正则表达式方法并使用matches而非equalToXml找到了解决方案

{
  "request": {
    "method": "ANY",
    "urlPattern": ".*/test.php",
    "bodyPatterns" : [{
      "matches": ".*<InvoiceNumber>6</InvoiceNumber>.*"
    }]
  },
  "response": {
    "status": 200,
    "bodyFileName": "sample.xml",
    "headers": {
      "Content-Type": "application/xml"
    }
  }
}

答案 1 :(得分:1)

您可能希望使用XPath匹配,如WireMock documentation中所述。 WireMock具有一些不错的XML功能,包括占位符,值得保留。

XPath

如果属性值是有效的XML,并且与提供的XPath表达式匹配,则认为匹配。如果XPath评估返回了任何元素,则认为XML文档匹配。 WireMock(通过XMLUnit)委托Java的内置XPath引擎,因此(至少)Java 8最多支持XPath 1.0版。

Java:

.withRequestBody(matchingXPath("//InvoiceNumber[text()='6']"))

JSON:

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