SoapUI用groovy脚本提取json数组数据

SOAPUI 中如何用Groovy 读取数据



前言:利用SoapUI进行数据源驱动测试,如果数据源是固定的,使用DataSource方法读取xls文件中的数据是很方便的,但是如果数据源不是固定的,需要从接口返回中的数据中动态获取的,这时就得动态去获取返回值的数据了。

在android中json数组数据是比较常见的,如先请求一组数据得到新闻列表,当点击列表中的新闻时,再根据ID去请求新闻正文。

例如如下数据,calendar_id是需要根据返回值动态获取的,此时需要通过获得数组中的calendar_id

{"calendar": 

{"calendar_id":"1705","showtime":"1288927800","endshowtime":"1288931400","allDay":false}, 
{"calendar_id":"1706","showtime":"1288933200","endshowtime":"1288936800","allDay":false},
{"calendar_id":"1709","showtime":"1288935600","endshowtime":"1288938900","allDay":false}

}

在SoapUI中可以通过groovy脚本实现提取json数组数据,提取到数据后就可以遍历访问列表中的每条新闻正文了

1.新建一个REST请求步骤,获取接口返回的数据

2.新建一个DataSource步骤,选择Groovy方式

3.添加一个名为cal_id的Properties

4.groovy编辑框中输入实现代码

  1. import groovy.json.JsonSlurper  
  2.   
  3. def xresponse = testRunner.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString  
  4. def slurper = new JsonSlurper()  
  5. def re = slurper.parseText(xresponse)  
  6. def num=re.calendar.size()  
  7. def i = testRunner.testCase.testSteps["DataSource"].currentRow  
  8. if(i<num)  
  9. {  
  10. result["cal_id"]=String.valueOf(re.calendar_id.id[i])  
  11. }  

5.新建一个Property Transfer步骤,将DataSource的cal_id传递给当前testCase的变量

6.新建 一个REST请求步骤,将得到的cal_id去请求另一个接口

7.新建一个DataSource Loop步骤,使DataSource与Property Transfer步骤循环,这样就可以遍历数组中的每个数据了


[reply]tz0705010216[/reply]
你好
以博文中的json为例,新增的groovy步骤则如下:
def xresponse = testRunner.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString  
def slurper = new JsonSlurper()  
def re = slurper.parseText(xresponse)
def id = re.calendar.calendar_id[i]    //i为json数组中的第i个子json对象
若为在脚本断言处添加groovy断言,则如下:
def xresponse = messageExchange.modelItem.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString
def slurper = new JsonSlurper()
def result = slurper.parseText(xresponse)

def id = re.calendar.calendar_id[i]    //i为json数组中的第i个子json对象



如需知道更加详细的内容,请在百度阅读输入SOAPUI 就可以找到


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值