线索响应取决于请求身体参数

问题描述 投票:2回答:3

我正在向Bodymock(Standalone,2.21)发送一个请求

{
        "attribute1": "value1",
        "attribute2": "value2",
        ...
        "attributen": "valuen"
}

使用/test/test-url到URL POST,没有查询参数。我希望它能做到以下几点:

  • 当attribute1等于“text1”时,以“response1.json”响应
  • 当attribute1等于“text2”时,以“response2.json”响应
  • 当attribute1等于“text1”或“text2”之外的其他内容时,使用“response_general.json”进行响应

其他属性与答案无关。我想通过只使用.json文件来做到这一点。谢谢!

json response wiremock
3个回答
0
投票

在更新版本的WireMock(2.19 +)中,支持HandleBars processing in the BodyFileName属性。然后,这允许您在JSON请求主体中放置(部分)名称,然后重用它的值作为文件名引用。

{
  "request" : {
    "urlPathPattern" : "/jpathFile",
    "method" : "GET",
    "headers": {
        "Content-Type": {
            "equalTo": "application/json"
        }
    }

  },
  "response" : {
    "status" : 200,
    "headers": {
        "Content-Type": "application/json"
    },
    "bodyFileName" : "/{{jsonPath request.body '$.attribute2'}}",
    "transformers": ["response-template"]
  }
}

输入消息:

{
    "attribute1": "value1",
    "attribute2": "response.json",
    "attributen": "valuen"
}

response.json位置的/__files/response.json

{
    "hello": "World!"
}

0
投票

答案是要检查身体模式,并为3种不同的情况设置3个映射:

一个用于检测到text1的情况:

       "request": {
          "method": "POST",
          "urlPattern":"/.*",
          "bodyPatterns": [
            {
              "contains":"\"attribute1\": \"text1\""
            }
          ]
        },
        "response": {
          "status": 200,
          "bodyFileName": "response_text1.json",
          "headers": {
            "Content-Type": "application/json"
          }
        }

一个是检测到text2的情况:

      "request": {
          "method": "POST",
          "urlPattern":"/.*",
          "bodyPatterns": [
            {
              "contains":"\"attribute1\": \"text2\""
            }
          ]
        },
        "response": {
          "status": 200,
          "bodyFileName": "response_text2.json",
          "headers": {
            "Content-Type": "application/json"
          }
        }

一个是没有检测到的情况。在这种情况下,给出一般答案。

        "request": {
            "method": "POST",
            "urlPattern": "/.*"
        },
        "response": {
              "status": 200,
              "bodyFileName": "response_general.json",
              "headers": {
                "Content-Type": "application/json"
              }
            }

0
投票

而不是使用“包含”或“equalTo”我建议使用“matchesJsonPath”

"bodyPatterns": [
        {
            "matchesJsonPath": "$[?(@.attribute1 == 'value1')]"
        }
]
© www.soinside.com 2019 - 2024. All rights reserved.