如何使用 Wiremock 提出具体要求?

How to make specific request by using Wiremock?

我尝试练习使用 Wiremock 创建模拟数据并像这样发送 JSON 正文请求


{ "petId ":"123"}


当petId为123、124、125时

应该显示响应请求是


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


当petId为250、251、252时


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


我创建映射 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"
        }
      }
    }
]
}

但它只适用于 petID 125 和 252 :(

您可以使用 OR operator

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

您还可以简化您的 matchesJsonPath 逻辑,使每个逻辑只包含一个正则表达式,例如...

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

查看JSON Path documentation.

下的Regex Matching例子