1

我从如下 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 循环使它更好,它一次解析每个集合,并为每个孩子一次断言“名称”、“状态”和“描述”的值

那可能吗?

4

1 回答 1

0

是的,这当然是可能的。

如果不了解更多关于您的实际数据,就不可能给出一个完美的例子,但您可以执行以下操作:

jsonSlurper.results?.eachWithIndex { result, i ->
    assert result.name == expectedNames[i]
    assert result.status == expectedStatus[i] // or just "Healthy" if that's the only one
    assert result.description == expectedDescriptions[i]
}

其中 expectedWhatever 是预期结果字段的列表。如果您的预期结果确实基于示例中的索引,那么您甚至可以在循环中计算它们,但我猜真实数据并非如此。

于 2018-05-11T21:40:23.547 回答