0

我正在使用wiremock来存根请求。我创建了一个 json 文件来获得响应:

{
    "request": {
        "method": "POST",
        "urlPath": "/nested/transform",
        "bodyPatterns": [
            {
                "matchesJsonPath": "$.name.[0].first"
            },
            {
                "matchesJsonPath": "$.name.[1].first"
            }
        ]
    },
    "response": {
        "status": 200,
        "body": "{\"firstName\": \"$(name.[0].first)\", \"lastName\": \"$(name.[1].first)\"}",
        "headers": {
            "Content-Type": "application/json"
        },
        "transformers": ["body-transformer"]
    }
}

我的请求和响应如下:

要求

{
"name": [
      {
        "first": "Vijay"
      },
      {
        "first": "Sagar"
      }
   ]
}

在这里,我收到了非常胡须的响应,并且没有按照我的意愿进行解析。

不是我预期的结果:

{
  "firstName": "[{first=Vijay}, {first=Sagar}]",
  "lastName": "[{first=Vijay}, {first=Sagar}]"
}

预期结果是:我愿意根据上述请求和存根 json 收到以下响应:

{"firstName": "Vijay","lastName": "Sagar"}

当我尝试了很多但无法匹配响应参数时,如何获得预期的结果?

4

1 回答 1

2

在处理 JSON 响应时,我更喜欢使用bodyFileName,因为它不需要转义。

__files/nested_json_template.json

{
    "firstName": "{{jsonPath request.body '$.name.[0].first'}}",
    "lastName": "{{jsonPath request.body '$.name.[1].first'}}"
}

映射/nested_json_mapping.json

{
    "request": {
        "method": "POST",
        "urlPath": "/nested/transform",
        "bodyPatterns": [
            {
                "matchesJsonPath": "$.name.[0].first"
            },
            {
                "matchesJsonPath": "$.name.[1].first"
            }
        ]
    },
    "response": {
        "status": 200,
        "bodyFileName": "nested_json.json",
        "headers": {
            "Content-Type": "application/json"
        },
        "transformers": ["response-template"]
    }
}
于 2020-01-28T19:24:30.343 回答