Wiremock standalone dynamic response array of objects is not working with bodyPatterns and matchesJsonPath

3k views Asked by At

I am using wiremock to stubbing the requests. I have created a json file to get a response:

{
    "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"]
    }
}

My request and response are as below:

Request

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

Here I receive very beard response and it is not parsed as I want.

Response which is not my expected result:

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

Expected result is: I'm willing to receive the following response based on above request and stubbed json:

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

How can I get the expected result as I tried a lot but was unable to match response parameters?

1

There are 1 answers

0
A. Kootstra On

When working with a JSON response, I prefer to use the bodyFileName as this that escaping isn't necessary.

__files/nested_json_template.json

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

mappings/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"]
    }
}