Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Matching with Wiremock

Tags:

xml

wiremock

I'm setting up a dummy PHP server with wiremock and want to match based upon one of the XML fields being passed. I basically will have multiple requests coming into this same url but the main difference between them will be the invoice number. My JSON for wiremock looks like this

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

This works fine when I use Postman and only pass an XML with the <InvoiceNumber></InvoiceNumber> field, but the moment I add a secondary field it fails.

I would like to be able to pass any Xml to wiremock and as long as it has the <InvoiceNumber></InvoiceNumber>field it will read it.

like image 209
Wollzy Avatar asked Jan 26 '23 04:01

Wollzy


2 Answers

You may wish to use XPath matching instead, as described in the WireMock documentation. WireMock has some nice XML functionality, including placeholders, that is worth keeping.

XPath

Deems a match if the attribute value is valid XML and matches the XPath expression supplied. An XML document will be considered to match if any elements are returned by the XPath evaluation. WireMock delegates to Java’s in-built XPath engine (via XMLUnit), therefore up to (at least) Java 8 it supports XPath version 1.0.

Java:

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

JSON:

{   "request": {
    ...
     "bodyPatterns" : [ {
      "matchesXPath" : "//InvoiceNumber[text()='6']"
    } ]
    ...   },   ... }
like image 118
Erica Kane Avatar answered Jan 29 '23 08:01

Erica Kane


Found the solution using a regex method and using matches instead of equalToXml

{
  "request": {
    "method": "ANY",
    "urlPattern": ".*/test.php",
    "bodyPatterns" : [{
      "matches": ".*<InvoiceNumber>6</InvoiceNumber>.*"
    }]
  },
  "response": {
    "status": 200,
    "bodyFileName": "sample.xml",
    "headers": {
      "Content-Type": "application/xml"
    }
  }
}
like image 25
Wollzy Avatar answered Jan 29 '23 06:01

Wollzy