如何在 WireMock JSON 存根中使用 if 条件?
How to use an if conditional in a WireMock JSON stub?
我需要在我的存根中使用 if 条件。我知道您可以使用 body 模式创建不同的场景,但这在我的情况下不起作用,因为我在有效负载中得到可变数量的 objects 并且我需要使用 for 循环来检查每一个。
所以我的请求负载看起来类似于:
[
{ "todo_id": 1 },
{ "todo_id": null },
{ "todo_id": 3 }
]
我想在有 todo_id
的地方响应,在有 null
的地方用随机整数响应,所以到目前为止我的响应负载是这样的:
"response": {
"status": 200,
"body": "[ {{#each (jsonPath request.body '$') as |todo|}}
{ \"todo_id\":
{{#if (todo.todo_id == null) }}
1{{randomValue length=1 type='NUMERIC'}}
{{else}}
{{todo.todo_id}}
{{/if}}
},
{{/each}} ]"
}
我知道你不能 body 那样隔开,但我这样做是为了让代码更容易阅读。
所以 for each 循环确实有效,我已经在没有 if 语句的情况下尝试过并且它工作正常。但是我无法让 if 语句为我工作。
关于如何实现这样的东西有什么想法吗?
好的,我在 WireMock 的 Google 组上得到了答案。
显然要比较您应该使用 eq
运算符的值。
所以将代码的条件部分更改为如下所示
{{#eq todo.todo_id null}}
1{{randomValue length=1 type='NUMERIC'}}
{{else}}
{{todo.todo_id}}
{{/eq}}
解决了问题。
我需要在我的存根中使用 if 条件。我知道您可以使用 body 模式创建不同的场景,但这在我的情况下不起作用,因为我在有效负载中得到可变数量的 objects 并且我需要使用 for 循环来检查每一个。 所以我的请求负载看起来类似于:
[
{ "todo_id": 1 },
{ "todo_id": null },
{ "todo_id": 3 }
]
我想在有 todo_id
的地方响应,在有 null
的地方用随机整数响应,所以到目前为止我的响应负载是这样的:
"response": {
"status": 200,
"body": "[ {{#each (jsonPath request.body '$') as |todo|}}
{ \"todo_id\":
{{#if (todo.todo_id == null) }}
1{{randomValue length=1 type='NUMERIC'}}
{{else}}
{{todo.todo_id}}
{{/if}}
},
{{/each}} ]"
}
我知道你不能 body 那样隔开,但我这样做是为了让代码更容易阅读。
所以 for each 循环确实有效,我已经在没有 if 语句的情况下尝试过并且它工作正常。但是我无法让 if 语句为我工作。
关于如何实现这样的东西有什么想法吗?
好的,我在 WireMock 的 Google 组上得到了答案。
显然要比较您应该使用 eq
运算符的值。
所以将代码的条件部分更改为如下所示
{{#eq todo.todo_id null}}
1{{randomValue length=1 type='NUMERIC'}}
{{else}}
{{todo.todo_id}}
{{/eq}}
解决了问题。