【发布时间】:2018-05-11 21:09:38
【问题描述】:
我从如下 Web 服务收到 JSON 响应。我想使用 Groovy Json slurper 解析结果节点的所有子节点并断言该值是正确的。
{
"status": "Healthy",
"results": [
{
"name": "Microservice one",
"status": "Healthy",
"description": "Url check MSOneURI success : status(OK)"
},
{
"name": "Microservice two",
"status": "Healthy",
"description": "Url check MSTwoURI success : status(OK)"
},
{
"name": "Microservice three",
"status": "Healthy",
"description": "Url check MSThreeURI success : status(OK)"
},
{
"name": "Microservice four",
"status": "Healthy",
"description": "Url check MSFourURI success : status(OK)"
},
{
"name": "Microservice five",
"status": "Healthy",
"description": "Url check MSFiveURI success : status(OK)"
}
]
}
这就是我所做的 - 这很有效。
//imports
import groovy.json.JsonSlurper
import groovy.json.*
//grab the response
def ResponseMessage = messageExchange.response.responseContent
// trim starting and ending double quotes
def TrimResponse =ResponseMessage.replaceAll('^\"|\"$','').replaceAll('/\\/','')
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(TrimResponse)
//verify the response to be validated isn't empty
assert !(jsonSlurper.isEmpty())
//verify the Json response Shows Correct Values
assert jsonSlurper.status == "Healthy"
def ActualMsNames = jsonSlurper.results*.name.toString()
def ActualMsStatus = jsonSlurper.results*.status.toString()
def ActualMsDescription = jsonSlurper.results*.description.toString()
def ExpectedMsNames = "[Microservice one,Microservice two,Microservice three,Microservice four,Microservice five]"
def ExpectedMsStatus = "[Healthy, Healthy, Healthy, Healthy, Healthy]"
def ExpectedMsDescription = "[Url check MSOneURI success : status(OK),Url check MSTwoURI success : status(OK),Url check MSThreeURI success : status(OK),Url check MSFourURI success : status(OK),Url check MSFiveURI success : status(OK)]"
assert ActualMsNames==ExpectedMsNames
assert ActualMsStatus==ExpectedMsStatus
assert ActualMsDescription==ExpectedMsDescription
但我想使用某种 for 循环使它更好,它会一次解析每个集合,并为每个孩子一次断言“名称”、“状态”和“描述”的值
这可能吗?
【问题讨论】:
-
只是好奇:如果您使用的是 SoapUI,为什么不使用内置断言之一呢?似乎 Content Assertion 非常适合这个。
-
感谢您的指点@SiKing。我们不能使用内置断言,部分原因是我的响应是 JSON 格式,并且 - 我们使用的是免费版本的 SOAP UI,它没有附带 JSON 路径匹配内容断言。
-
付费版也不行! SoapUI 在内部将所有内容都转换为 XML。因此,您可以将 XPath 断言用于任何类型的响应。
标签: groovy soapui jsonslurper