如何遍历 JSON 中的 DTO 以执行断言?
How to iterate through a DTOs in a JSON to perform assertions?
我是编程初学者,目前我正在执行依赖 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'
谢谢
您可以将断言简化为一行,例如:
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
我是编程初学者,目前我正在执行依赖 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'
谢谢
您可以将断言简化为一行,例如:
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