Wiremock BodyPattern 匹配包含这个或那个

Wiremock BodyPattern matching Contains this or that

如果请求正文包含这个或那个等,我正在尝试将 Wiremock 配置为 return 来自文本文件的相同响应。这是我的单个请求的工作文件:

{
  "priority": 1,
  "request": {
    "method": "POST",
    "urlPath": "/v1/retrieve-vehicle",
    "bodyPatterns" : [ {
      "contains" : "\"vehicleIdentifier\":\"EROR-103\""
    } ]
  },
  "response": {
    "status": 404,
    "bodyFileName": "JsonFiles/NoVinFound-Error103.json",
    "headers": {
      "Content-Type": "application/json;charset=UTF-8"
    }
  }
}

我尝试了 bodyPatterns 属性的几种组合(受文档启发)但无济于事。

"bodyPatterns" : [ {
      "contains" : "\"vehicleIdentifier\":\"EROR-103\"",
      "contains" : "\"vehicleIdentifier\":\"EROR-103A\""
    } ]
"bodyPatterns" : [ {
      "contains" : "\"vehicleIdentifier\":\"EROR-103\""
      }, {
      "contains" : "\"vehicleIdentifier\":\"EROR-103A\""
    } ]
"multipartPatterns" : [ {
      "matchingType" : "ANY",
      "bodyPatterns" : [ {
        "contains" : "\"vehicleIdentifier\":\"EROR-103\"",
        "contains" : "\"vehicleIdentifier\":\"EROR-103A\""
      } ]
    } ]
"multipartPatterns" : [ {
      "matchingType" : "ANY",
      "bodyPatterns" : [ {
        "contains" : "\"vehicleIdentifier\":\"EROR-103\"" 
        }, {
        "contains" : "\"vehicleIdentifier\":\"EROR-103A\""
      } ]
    } ]

请指教我做错了什么。谢谢!

我的一位同事找到了解决方案。我们需要一个 'mappings tag',然后列出完整的 JSON 个对象,如下所示。

{
  "mappings": [
    {
      "priority": 1,
      "request": {
        "method": "POST",
        "urlPath": "/v1/retrieve-owner",
        "bodyPatterns" : [ {
          "matchesJsonPath": "$.[?($.vehicleIdentifier == 'VIN-A')]"

        } ]
      },
      "response": {
        "status": 200,
        "bodyFileName": "JsonFiles/Exported-Vehicle.json",
        "headers": {
          "Content-Type": "application/json;charset=UTF-8"
        }
      }
    },
    {
      "priority": 1,
      "request": {
        "method": "POST",
        "urlPath": "/v1/retrieve-owner",
        "bodyPatterns" : [ {
          "matchesJsonPath": "$.[?($.vehicleIdentifier == 'VIN-B')]"

        } ]
      },
      "response": {
        "status": 200,
        "bodyFileName": "JsonFiles/Exported-Vehicle.json",
        "headers": {
          "Content-Type": "application/json;charset=UTF-8"
        }
      }
    }
  ]
}

使用 mappings 文件可以,但有一些注意事项,总的来说我建议采用不同的方法。

相反,您可以拥有一个基于正则表达式匹配的单一映射文件。

{
    "priority": 1,
    "request": {
        "method": "POST",
        "urlPath": "/v1/retrieve-owner",
        "bodyPatterns" : [ {
            "matches": ".*\"vehicleIdentifer\": \"VIN-(A|B)\".*"
        } ]
    },
    "response": {
        "status": 200,
        "bodyFileName": "JsonFiles/Exported-Vehicle.json",
        "headers": {
            "Content-Type": "application/json;charset=UTF-8"
        }
    }
}

您可能需要尝试让正则表达式正确匹配,但这应该可行并让您更加灵活。假设您必须添加另一个匹配项,您只需编辑正则表达式,而不是将一个全新的映射添加到映射文件。

我对 matchesJsonPath 也没有太多经验,但您也可以利用它并让正则表达式匹配那里的值。

这是我个人最喜欢的使用正则表达式的工具:Regex101