簡體   English   中英

Wiremock響應取決於請求正文參數

[英]Wiremock response depending on request body parameter

我正在向Wiremock(Standalone,2.21)發送請求

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

使用POST到URL /test/test-url ,沒有查詢參數。 我希望它執行以下操作:

  • 當attribute1等於“ text1”時,以“ response1.json”響應
  • 當attribute1等於“ text2”時,以“ response2.json”響應
  • 當attribute1等於“ text1”或“ text2”以外的其他內容時,以“ response_general.json”響應

其他屬性與答案無關緊要。 我只想通過使用.json文件來做到這一點。 謝謝!

在WireMock(2.19+)的最新版本中,BodyFileName屬性支持HandleBars處理 然后,您可以將(部分)名稱放入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!"
}

答案是要檢查身體形態,並針對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"
              }
            }

我建議不要使用“ contains”或“ equalTo”,而建議使用“ matchesJsonPath”

"bodyPatterns": [
        {
            "matchesJsonPath": "$[?(@.attribute1 == 'value1')]"
        }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM