如何循环访问 JSON 中的 DTO 以执行断言



我是编程初学者,目前我正在执行依赖于时髦脚本的SOAP UI测试。下面我想断言策略 DTO 中的所有内容都包含正确的值:

{
   "policies":    [
            {
         "xx": 28,
         "xxxxx": 41,
      },
            {
         "xx": 31,
         "xxxxxx": 41,
      },
            {
         "xx": 34,
         "xxxxx": 41,
      },
            {
         "xx": 37,
         "xxxxx": 41,
      }
   ]
   }

现在我知道如何通过简单地包含json.policies.xx[0]json.policies.xx[1]等来执行断言,但这似乎有点冗长。我假设有一种更好的方法,即在策略中遍历 DTO,以确保 xxx 正确且 xxxxx 正确。我的问题是,有人可以给我一个示例供我使用以了解如何编码吗?

import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json =  new JsonSlurper().parseText(response)
assert json.policies.xx[0].toString() = '28'
assert json.policies.xx[1].toString() = '31'
assert json.policies.xx[2].toString() = '34'
assert json.policies.xx[3].toString() = '37'
assert json.policies.xxxxx[0].toString() = '41'
assert json.policies.xxxxx[1].toString() = '41'
assert json.policies.xxxxx[2].toString() = '41'
assert json.policies.xxxxx[3].toString() = '41'

谢谢

您可以将断言简化为一行,例如:

import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json =  new JsonSlurper().parseText(response)
def policies = [[xx: 28, xxxxx: 41], [xx: 31, xxxxx: 41], [xx: 34, xxxxx: 41], [xx: 37, xxxxx: 41]]
assert json.policies == policies

最新更新