如何迭代JSON中的DTO来执行断言?

问题描述 投票:1回答:1

我是编程的初学者,目前我正在执行依赖于groovy脚本的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'

谢谢

json groovy soapui
1个回答
1
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.