如何在Spring Cloud Contract测试中从json响应中验证密钥格式?
比方说,我有一个类似json的响应:
{
"products": {
"0": {
"type": "food",
"name": "pizza"
},
"9": {
"type": "drink",
"name": "wine"
}
}
}
合同测试如下:
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description 'Dynamic key example'
request {
method 'GET'
urlPath '/products/all'
}
response {
status 200
headers {
contentType applicationJsonUtf8()
}
body(
[
"products": [
"0": [
"type": $(anyOf("food", "drinks")),
"name" : $(nonBlank()),
]
]
]
)
}
}
产品ID("0"
和"9"
)可以采用任何正整数值。我想在合同测试中验证产品ID。但是,如果我用"0"
替换合同中的$(consumer("0"), producer(regex("^\\d*\$")))
,它将失败。
任何想法如何解决这个问题?可能吗?
P.S。我没有更改协议的可能性
答案 0 :(得分:1)
问题出在常规地图语法中:($(consumer("0"), producer(regex("^\\d*\$"))))
完整答案:
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description 'Dynamic key example'
request {
method 'GET'
urlPath '/products/all'
}
response {
status 200
headers {
contentType applicationJsonUtf8()
}
body(
[
"products": [
($(consumer("0"), producer(regex("^\\d*\$")))): [
"type": $(anyOf("food", "drinks")),
"name" : $(nonBlank()),
]
]
]
)
}
}