Search code examples
jsonpathwiremockwiremock-standalone

Using regex to negate a filter in wiremock jsonpath


I am using wiremock for stubbing and it uses Jayway JsonPath.

I want to create a stub only when the json element doesn't contain exactly 10 digits.

stub is

"request": {
    "bodyPatterns": [
      {
        "matchingJsonPath": "$.employees[?(@.employeeContact =~/[^0-9]{10}/)]"
      }
    ]
  }

I have tried multiple combinations like:

1. $.employees[?(@.employeeContact =~/[^0-9]{10}/)]
2. $.employees[?(@.employeeContact =~/^[0-9]{10}/)]
3. $.employees[?(@.employeeContact !=~/[0-9]{10}/)]
4. $.employees[?(@.employeeContact <>~/[^0-9]{10}/)]

But none of these have worked. Example json which should NOT work:

{
"employee": {
    "employeeContact": "1234567890"
}
}

while these employee should work (anything other than 10 digits):

 1. "employeeContact": "1a34567890"  // character in between
 2. "employeeContact": "12345678901" // more than 10
 3. "employeeContact": "123456789"   // less than 10
 4. "employeeContact": "123456 89"   //space 

Solution

  • This is what worked for me:

    "bodyPatterns": [{
        "matchesJsonPath": "$.employees[?(@.employeeContact =~/[^0-9]{1,9}/ || $.employees[?(@.employeeContact =~/[^0-9]{11,}/)]" 
        }]
    

    Watch that it is matchesJsonPath instead of matchingJsonPath. Even with that "or" didnt work with my wiremock 2.28.1 so may well be a wiremock bug.