0

Using wiremock-standalone (version 2.29.1), I want to verify a request with its body holding an array of objects, containing optional properties.

For instance, consider this request:

Request body (JSON format)

    { 
      "foo": [ 
        { "bar": "1" },
        { "qux": "oh hai" },
        { "bar": "ohnoes" }
      ]
    }

And let's say I want to match requests only if all the foo.bar attributes are either present, or contain only a single digit (it's only for the sake of example). The example above should not match (the third object has a bar attributes with non-digits characters).

I tried different approches, and the closest I got is this:

{ 
  "matchesJsonPath": {
    "expression": "$.foo[*].bar",
    "or": [
      { "matches": "^\\d$" },
      { "absent": true }
    ]
  }
}

There are 2 problems:

  • if there is no bar attribute at all, the request does not match
  • if at least 1 bar attribute passes the check, then the whole request passes, even though other bar values are invalid (the example above passes)

Does anyone know how to create such a rule in wiremock?

scottinet
  • 171
  • 2
  • So your request body is an array of JSON objects, which could contain either fieldA or fieldB? And you want to match when either fieldA or fieldB is found in each JSON object? – agoff Aug 16 '21 at 13:19

1 Answers1

0

I found a possible solution, maybe not the easiest but it works.

Following your example:

request:

{ 
  "foo": [ 
    { "bar": "1" },
    { "qux": "oh hai" },
    { "bar": "ohnoes" }
  ]
}

This bodyPatterns file works for validate each field is present and it has the value given:

"bodyPatterns" : [

      {
        "matchesJsonPath": "$.foo[?(@.bar == '1')]"
      },

      {
        "matchesJsonPath": "$.foo[?(@.qux == 'oh hai')]"
      },

      {
        "matchesJsonPath": "$.foo[?(@.bar == 'ohnoes')]"
      }
]

For reference, the following post helped me a lot:

Wiremock matchesJsonPath checking array values ignoring the order

  • Just to chip in, how to handle if all the objects have the same name i.e., there are 3 bar objects and you want to send a response back for all 3 considering each ones value? – code-monkey Apr 08 '22 at 10:46