简体   繁体   English

JSON 有效负载的 Wiremock 请求模板,具有多个允许的密钥,但响应相同

[英]Wiremock Request Templating for JSON Payload with multiple allowed keys, but same response

Trying to mock an API endpoint that allows a request with 2 possible payloads, but the same response:尝试模拟一个 API 端点,该端点允许具有 2 个可能有效负载的请求,但响应相同:

Request Option 1请求选项 1

{
  "key1": "value1"
}

Request Option 2请求选项 2

{
  "key2": "value2"
}

Based on the Request Templating documentation , I see that there's an option to define some regex for matchesJsonPath .根据请求模板文档,我看到有一个选项可以为matchesJsonPath定义一些正则表达式。 However, I'm unable to figure out how to provide a configuration that will allow key1 or key2 .但是,我无法弄清楚如何提供允许key1key2的配置。

This is what I'd tried, but it doesn't seem to work:这是我尝试过的,但它似乎不起作用:

{
  // ... other configs
  "request": {
    "bodyPatterns": [
      {
        "matchesJsonPath": "$.(key1|key2)"
      }
    ]
  }
}

Is it possible to provide 1 definition that supports both payloads, or do I have to create 2 stubs?是否可以提供 1 个支持两种有效负载的定义,还是必须创建 2 个存根?

Note: I am using a standalone Wiremock Docker image , so options for more complex handling using Java are limited.注意:我使用的是独立的 Wiremock Docker 图像,因此使用 Java 进行更复杂处理的选项是有限的。

Your JsonPath matcher is formatted incorrectly.您的 JsonPath 匹配器格式不正确。 You need to apply a filter/script (denoted by ?() ).您需要应用过滤器/脚本(由?()表示)。 More information about how JsonPath matchers work can be found here.可以在此处找到有关 JsonPath 匹配器如何工作的更多信息。

Here is what the properly formatted JsonPath matcher could look like:以下是正确格式化的 JsonPath 匹配器的样子:

{
  "matchesJsonPath": "$[?(@.key1 || @.key2)]"
}

If you need the key1 and key2 to have specific values, that would look like:如果您需要key1key2具有特定值,则如下所示:

{
  "matchesJsonPath": "$[?(@.key1 == 'value1' || @.key2 == 'value2')]"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM