Warm tip: This article is reproduced from serverfault.com, please click

Validate/Match JSON field for number and not string in the input request in Wiremock

发布于 2020-12-26 20:36:12

I am trying to validate a particular json field amount in the request to have number and not string

{
  "request": {
    "method": "POST",
    "urlPath": "/charges",
    "bodyPatterns" : [
      {"matchesJsonPath" : "$[?(@.amount =~ /^[0-9]*$/i)]"}
    ]
}

Now request1 and request2 are working fine and request3 fails. But I expect request2 to fail as well because it is a string and not number as it is in double quotes.

Request 1,

{
    "amount": 123,
}

Request 2,

{
    "amount": "123",
}

Request 3,

{
    "amount": "a123",
}

Is this possible?. I see in wiremock docs

    Since WireMock’s matching operators all work on strings, 
the value selected by the JSONPath expression will be coerced to a string before the match is evaluated.
Questioner
firstpostcommenter
Viewed
0
firstpostcommenter 2020-12-28 17:43:56

I found a workaround.

As per the regex you have given, I see that the amount field cannot have negative values.

So in the matchesJsonPath, do a dummy check that the value is greater than or equal to zero. This will make sure that the value 123 will work but "123" will throw an error

You wouldn't even need to use the regex anymore.

{
  "request": {
    "method": "POST",
    "urlPath": "/charges",
    "bodyPatterns" : [
      {"matchesJsonPath" : "$[?(@.amount >= 0)]"}
    ]
}