我正在独立使用 Wiremock,下面是请求/响应的示例。 jsonPath 不起作用,它正在返回整个代码。我做错了什么?
索取样品
{
"source": "Web",
"orders":[
{
"id": "Order1",
"status": "In Progress"
},
{
"id": "Order2",
"status": "In Progress"
}
]
}
预期反应
{
"user": "User1",
"orders": [
{
"id": "Order1",
"status": "In Progress",
"shipping": "Pending"
},
{
"id": "Order2",
"status": "In Progress",
"shipping": "Pending"
}
]
}
我的回复.json
{
"user": "User1",
"orders": [
{{#each (jsonPath request.body '$.batches') as |batches|}}
{
"id": "{{{batches.id}}}",
"status": "In Progress",
"shipping": "Pending"
}{{^last}},{{/last}}
{{//each}}
]
}
实际反应
{
"user": "User1",
"orders": [
{{#each (jsonPath request.body '$.batches') as |batches|}}
{
"id": "{{{batches.id}}}",
"status": "In Progress",
"shipping": "Pending"
}{{^last}},{{/last}}
{{//each}}
]
}
通常,当没有解析任何内容时,这意味着未为此响应启用响应模板。要启用响应模板,您可以通过添加
transformers
字段将其添加到存根映射中:
"name" : "orders",
"request" : {
"url" : "/orders",
"method" : "GET"
},
"response": {
"status": 200,
"bodyFileName": "response.json",
"transformers": [
"response-template"
],
"headers": {
"Content-Type": "application/json"
}
}
}
使用上面的存根映射和这个
response.json
文件:
{
"user": "User1",
"orders": [
{{#each (jsonPath request.body '$.orders') as |order|}}
{
"id": "{{order.id}}",
"status": "In Progress",
"shipping": "Pending"
} {{#not @last}},{{/not}}
{{/each}}
]
}
我能够产生您正在寻找的输出。这个要求:
{
"source": "Web",
"orders": [
{
"id": "Order1",
"status": "In Progress"
},
{
"id": "Order2",
"status": "In Progress"
},
{
"id": "Order3",
"status": "In Progress"
}
]
}
从wiremock产生此输出:
{
"user": "User1",
"orders": [
{
"id": "Order1",
"status": "In Progress",
"shipping": "Pending"
},
{
"id": "Order2",
"status": "In Progress",
"shipping": "Pending"
},
{
"id": "Order3",
"status": "In Progress",
"shipping": "Pending"
}
]
}
jsonPath
与响应中的数组匹配,并且 each
循环遍历这些元素。 not
检查它是否是循环中的最后一个元素,如果不是,则添加 ,
以使响应有效 json。
这里对条件逻辑和迭代有很好的解释 - https://docs.wiremock.io/response-templatating/conditional-logic-and-iteration/
这一切都是使用最新版本的wiremock完成的。