Home > OS >  How to make specific request by using Wiremock?
How to make specific request by using Wiremock?

Time:10-01

I try to practice creating mock data with Wiremock and send JSON body request like this


{ "petId ":"123"}


When petId is 123, 124, 125

It should show response request is


{ "petType":"1", "wildLevel":"40"}


When petId is 250, 251, 252


{ "petType":"2", "wildLevel":"80"}


and I create mapping JSON


{
  "mappings": [
{
      "request": {
        "method": "POST",
        "urlPath": "/mock/animal/status",
        "bodyPatterns": [
          {
            "matchesJsonPath": "$[?(@.petType== '123')]",
            "matchesJsonPath": "$[?(@.petType== '124')]",
            "matchesJsonPath": "$[?(@.petType== '125')]",
          }
        ]
      },
      "response": {
        "status": 200,
        "transformers": ["response-template"],
        "bodyFileName": "animal-success-40-200.json",
        "headers": {
          "Content-Type": "application/json"
        }
      }
    },
{
      "request": {
        "method": "POST",
        "urlPath": "/mock/animal/status",
        "bodyPatterns": [
          {
            "matchesJsonPath": "$[?(@.petType== '250')]",
            "matchesJsonPath": "$[?(@.petType== '251')]",
            "matchesJsonPath": "$[?(@.petType== '252')]",
          }
        ]
      },
      "response": {
        "status": 200,
        "transformers": ["response-template"],
        "bodyFileName": "animal-success-80-200.json",
        "headers": {
          "Content-Type": "application/json"
        }
      }
    }
]
}

but it works just petID 125 and 252 :(

CodePudding user response:

You could use the OR operator.

...
"bodyPatterns": [
  {
    "OR": [
      { "matchesJsonPath": "$[?(@.petType== '250')]" },
      { "matchesJsonPath": "$[?(@.petType== '251')]" },                      
      { "matchesJsonPath": "$[?(@.petType== '252')]" },
    ]
  },
...

You could also simplify your matchesJsonPath logic to only include a single regex for each, something like...

...
"matchesJsonPath": "$[?(@.petType =~ /25(0|1|2)/)]"
...

Look at the Regex Matching examples under the JSON Path documentation.

  • Related