2017-02-26 37 views
1

检查每个json响应值实例的最动态方式是否与脚本断言中的另一个json响应值匹配?如何检查与json响应中的另一个相关值匹配的值

我的意思是可以说我有以下以下回应:

{ 
    "xxx": [{ 
      "roomInformation": [{ 

       "xxx": xxx 

      }], 

      "totalPrice": xxx 
     }, 

     { 
      "roomInformation": [{ 
       xxx: xxx 
      }], 
      "totalPrice": xxx 
     } 
    ] 

} 

我要检查的第一个房间的价格与第一totalPrice和第二roomPrice匹配,以配合第二totalPrice。它必须是动态的,因为我可能会得到许多不同的实例,所以我不能简单地用[0]和[1]来查看json。实际检查每个roomPrice与其相应的totalPrice匹配。

由于

+1

你有一些有效的JSON吗?你的问题中的JSON是无效的... –

+0

我会给你一些有效的json – BruceyBandit

+0

你使用已经验证副本的主/副本,并且当前响应将与它进行比较吗? – Rao

回答

1

这里是script assertion检查每个roomPrice是匹配或不与totalPrice

编辑:基于OP的充分响应提供here

脚本断言

//Check if the response is not empty 
assert context.response, "Response is empty or null" 

def json = new groovy.json.JsonSlurper().parseText(context.response) 
def sb = new StringBuffer() 
json.regions.each { region -> 
    region.hotels.each { hotel -> 
     (hotel?.totalPrice == hotel?.roomInformation[0]?.roomPrice) ?: sb.append("Room price ${hotel?.roomInformation[0]?.roomPrice} is not matching with total price ${hotel.totalPrice}")  
    } 
} 
if (sb.toString()) { 
    throw new Error(sb.toString()) 
} else { log.info 'Prices match' } 
+0

我试着饶与蒂姆的回答 – BruceyBandit

+0

根据您的其他答案,它可能需要在脚本中的更改。 – Rao

2

所以给出的JSON作为一个变量:

def jsonTxt = '''{ 
    "hotels": [{ 
      "roomInformation": [{ 

       "roomPrice": 618.4 

      }], 

      "totalPrice": 618.4 
     }, 

     { 
      "roomInformation": [{ 
       "roomPrice": 679.79 
      }], 
      "totalPrice": 679.79 
     } 
    ] 

}''' 

然后,我们可以使用下面的脚本:

import groovy.json.* 

new JsonSlurper().parseText(jsonTxt).hotels.each { hotel -> 
    assert hotel.roomInformation.roomPrice.sum() == hotel.totalPrice 
} 

正如您所看到的,我使用sum将所有roomInformation.roomPrice值一起添加。在你的例子中,你只有一个价格,所以这将是罚款..而且它也将涵盖你有多个房间合计的情况,以使总数为

+0

是“酒店”,就像每个'酒店'的变量名称? – BruceyBandit

+0

另外,如果我想测试以查看log.info的值,那么编写log.info的正确方法是确保它的正确性? – BruceyBandit

+0

@BruceyBandit是的,'hotel'是'hotels'中'each'元素的变量的名称。如果您想注销,只需执行'log.info'个人:$ {hotel.roomInformation.roomPrice} == total:$ {hotel.totalPrice}“'或类似 –

相关问题