代码之家  ›  专栏  ›  技术社区  ›  Big Hendo npocmaka

如何在JSON中迭代DTO以执行断言?

  •  1
  • Big Hendo npocmaka  · 技术社区  · 8 年前

    我是一名编程新手,目前正在执行依赖groovy脚本的SOAP UI测试。下面我想断言,策略DTO中的所有内容都包含正确的值:

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

    现在我知道了如何通过简单的include来执行断言 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'
    

    非常感谢。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Big Hendo npocmaka    8 年前

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

    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