出处:https://www.jianshu.com/p/ce6f8a1f66f4

一、一些内部元件的访问

  1. testRunner.testCase开头

1、向下访问

  1. testRunner.testCase.testSteps[testStepName]
  2. testRunner.testCase.getTestStepByName("新增一个空间")

2、向上访问,用于访问同一项目中的其他testSuites 和 testCase下的元素

  1. testRunner.testCase.testSuite.project.testSuites[testSuiteName].testCases[testCaseName].testSteps[testStepName]

3、几乎所有元件都有get 和set属性的方法

  1. setPropertyValue getPropertyValue
  2. //在下面的4,5,6点中,几乎所有的属性值都可以和对应的get方法互相替换等价

4、获取响应体

  1. myResponse=testRunner.testCase.getTestStepByName("新增一个空间").testRequest.response
  2. myRequest=testRunner.testCase.getTestStepByName("新增一个空间").testRequest
  3. 可以替换使用:getTestRequest(),testSteps[testStepName],getResponse()等。
  4. 比较特殊的2
  5. 获取响应作为String
  6. myResponse.contentAsString 或者 myRequest.getResponseContentAsString()
  7. 获取响应作为Xml
  8. myResponse.contentAsXml 或者myRequest.getResponseContentAsXml()

5、响应头和请求头

响应头:

  1. testRunner.testCase.getTestStepByName("新增一个空间").testRequest.response.responseHeaders["Location"]
  2. 或者testRunner.testCase.getTestStepByName("查询空间详情").testRequest.getResponse().getResponseHeaders("Location")

请求头:

  1. testRunner.testCase.getTestStepByName("查询空间详情").testRequest.requestHeaders
  2. testRunner.testCase.getTestStepByName("查询空间详情").testRequest.getRequestHeaders("Location")

设置请求头

  1. def headerMap = new StringToStringMap() //
  2. headerMap.put("headerKeyName","HeaderKeyWord") //添加到map
  3. testRunner.testCase.getTestStepByName("查询空间详情").testRequest.setRequestHeaders(headerMap)

6、获取请求地址

  1. testRunner.testCase.getTestStepByName("查询空间详情").testRequest.path

7、getAt(String) 方法,传入property名字,检索出值

  1. 针对testRunner下的所有对象,都可以通过此方法直接获取到 属性,例如:
  2. testRunner.testCase.getTestStepByName("查询空间详情").testRequest.getAt("path")
  3. 对应:testRunner.testCase.getTestStepByName("查询空间详情").testRequest.path
  4. testRunner.testCase.getTestStepByName("查询空间详情").testRequest.response.getAt("responseHeaders")
  5. 对应:testRunner.testCase.getTestStepByName("查询空间详情").testRequest.requestHeaders

8、获取全部用例并循环

  1. def testCaseList = testRunner.testCase.testSuite.getTestCaseList()
  2. testCaseList.each{
  3. if(it.testSteps["Input"])
  4. it.testSteps["Input"].setPropertyValue("spaceid",uid)
  5. }

9、相对的获取用例数,getTestCaseCount()

  1. for(int i=0; i<testSuite.getTestCaseCount(); i++) {
  2. if (!testSuite.getTestCaseAt(i).isDisabled()) {
  3. if (!(testSuite.getTestCaseAt(i).getTestStepByName("stepName")).equals()){
  4. .....
  5. }
  6. }
  7. }

10、获取getTestSuiteCount()

  1. testRunner.testCase.testSuite.project.getTestSuiteCount()

11、获取名称

  1. 部分元件只有LabelName中的一个,测试一下就知道了。
  2. getLabel() getName()大多数情况是等价的
  3. a. test case的名称
  4. def tc = testRunner.testCase;
  5. log.info (tc.getLabel());
  6. b. test suite的名称
  7. def ts = testRunner.testCase.testSuite;
  8. log.info (ts.getLabel());
  9. getName()
  10. project 名称
  11. def tp = testRunner.testCase.testSuite.project;
  12. log.info (tp.getName());

12、在断言中需要使用用例对象的话

  1. messageExchange.modelItem.testCase.testSteps["Properties"].getPropertyValue("userId")

13、全局属性变量访问

  1. 对于项目中的属性可分为这么几个级别Global, Project,TestSuite, TestCase
  2. 即全局变量、项目级别、用例集级别、单个用例级别
  3. 要获得如项目级别的属性变量的话,可以用以下方法
  4. def time_num=context.expand('${#Project#time_num}') //##号内为定义哪个级别的属性变量,后面为属性名

二、json操作

1、json builder

  1. def createAuthorId = context.expand( '${查询空间详情#Response#$.createAuthorId}' )
  2. def flag = "1"
  3. import groovy.json.JsonBuilder
  4. def json = new JsonBuilder()
  5. json {
  6. userID createAuthorId
  7. fileflag flag}
  8. return json

2、json 解析

  1. json为:
  2. {"calendar": [ {"calendar_id":"1705","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
  3. {"calendar_id":"1706","showtime":"1288933200","endshowtime":"1288936800","allDay":false},
  4. {"calendar_id":"1709","showtime":"1288935600","endshowtime":"1288938900","allDay":false}
  5. ] }
  6. import groovy.json.JsonSlurper
  7. def xresponse = testRunner.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString
  8. def slurper = new JsonSlurper()
  9. def re = slurper.parseText(xresponse)
  10. //访问顶级元素,返回的是一个列表使用size 获得长度
  11. re.calendar re.calendar.size()
  12. //访问元素模式
  13. re.calendar.calendar_id re.calendar.calendar_id[index]
  14. //另一种访问形式
  15. re['calendar']['calendar_id'][index]
  16. //查找过滤
  17. re.calendar.calendar_id.find{it=='1706'} //获得的结果是 calendar_id 1706
  18. re.calendar.find{it.calendar_id=='1706'} //获得的是calendar元素

三、XML操作(解析)

  1. ef groovyUtils = new com.eviware.soapui.support.GroovyUtils(context )
  2. //获取上下文对象,转化成groovyUtils对象
  3. defwsdlResponse=testRunner.testCase.testSteps["发贴"].getTestRequest().getResponseContentAsXml()
  4. log.info("wsdlResponse==="+wsdlResponse)
  5. //获取指定步骤的返回信息并转化成xml
  6. holder = groovyUtils.getXmlHolder(wsdlResponse)
  7. //获取指定节点的值
  8. defmessage=holder.getNodeValue("//ns1:Response[1]/ns1:response[1]/ns1:e[1]/ns1:message[1]")
  9. log.info("获得节点对应的值是"+message)
  10. deffandom_creator_sn=holder.getNodeValue("//ns1:fandom_creator_sn")
  11. log.info("获得节点对应的值是"+fandom_creator_sn)

四、文件操作

直接百度groovy文件操作就好了,用得少不收集了

五、各级别的集合操作

1、TestSteps的操作

  1. testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].testCases["空间管理测试"].testSteps
  2. =getTestSteps()。都是获取用例下的testStep列表,返回的是 key=object 形式的字典map
  3. getTestStepList() 获取用例下的testStep列表,纯列表
  4. getTestStepCount() 获取数量
  5. getTestStepAt(int) getTestStepById(java.util.UUID) 通过位置和UUID 查找step
  6. getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class) 通过类型过滤查找得到 testSteps列表。

2、testCases操作

  1. testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].testCases=getTestCases()
  2. 返回的是 key=object 形式的字典map
  3. getTestCaseList(), 获取的列表,纯列表
  4. getTestCaseCount(), 获取数量
  5. getTestCaseAt(int), getTestCaseById(java.util.UUID) 通过位置和UUID

3、testSuites操作

  1. testRunner.testCase.testSuite.project.testSuites=getTestSuites()
  2. 返回的是 key=object 形式的字典map
  3. getTestSuiteList(),获取的列表,纯列表
  4. getTestSuiteCount() 获取数量
  5. ,getTestSuiteAt(int), getTestSuiteById(java.util.UUID) 通过位置和UUID

4、返回是list时操作

  1. testCaseList=testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].getTestCaseList()
  2. log.info testCaseList[0] //使用 index访问
  3. //each循环
  4. testCaseList.each{
  5. it.xxxxx
  6. }

5、返回是map时操作

  1. testStepsMap=testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].testCases["空间管理测试"].testSteps
  2. //使用名称key访问
  3. log.info testStepsMap["新增一个空间"]
  4. log.info testStepsMap.get("新增一个空间")
  5. //遍历 使用默认闭包it
  6. testStepsMap.each{
  7. log.info it.key+" "+it.value
  8. }
  9. //使用自定义闭包名称遍历
  10. testStepsMap.each{myp->
  11. log.info myp.key+" "+myp.value
  12. }

六、数据库操作

1、普通的jdbc编程

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. public class JDBCExample1 {
  7. public static void main(String[] args) {
  8. Connection con = null;
  9. Statement stmt = null;
  10. ResultSet rs = null;
  11. try{
  12. Class.forName("org.gjt.mm.mysql.Driver");
  13. con = DriverManager.getConnection("jdbc:mysql://localhost:3306/words",
  14. "words", "words");
  15. stmt = con.createStatement();
  16. rs = stmt.executeQuery("select * from word");
  17. while (rs.next()) {
  18. System.out.println("word id: " + rs.getLong(1) +
  19. " spelling: " + rs.getString(2) +
  20. " part of speech: " + rs.getString(3));
  21. }
  22. }catch(SQLException e){
  23. e.printStackTrace();
  24. }catch(ClassNotFoundException e){
  25. e.printStackTrace();
  26. }finally{
  27. try{rs.close();}catch(Exception e){}
  28. try{stmt.close();}catch(Exception e){}
  29. try{con.close();}catch(Exception e){}
  30. }
  31. }
  32. }

2、grrovy sql

  1. import groovy.sql.Sql
  2. sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words",
  3. "words", "org.gjt.mm.mysql.Driver")

查出所有行

  1. sql.eachRow("select * from word"){ row |
  2. println row.word_id + " " + row.spelling + " " + row.part_of_speech
  3. }

执行插入操作

  1. wid = 999
  2. spelling = "Nefarious"
  3. pospeech = "Adjective"
  4. sql.execute("insert into word (word_id, spelling, part_of_speech)
  5. values (${wid}, ${spelling}, ${pospeech})")

使用位置参数

  1. val = sql.execute("select * from word where word_id = ?", [5])

更新

  1. nid = 5
  2. spelling = "Nefarious"
  3. sql.executeUpdate("update word set word_id = ? where spelling = ?", [nid, spelling])

删除

  1. sql.execute("delete from word where word_id = ?" , [5])

创建数据集

  1. sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words",
  2. "words", "org.gjt.mm.mysql.Driver")
  3. words = sql.dataSet("word")
  4. words.each{ word |
  5. println word.word_id + " " + word.spelling
  6. }
  7. words.add(word_id:"9999", spelling:"clerisy", part_of_speech:"Noun")

查询结果集的访问

  1. sql.eachRow("select * from word"){ grs |
  2. println "-1 = " + grs.getAt(-1) //使用索引访问最后一个
  3. println "2 = " + grs.getAt(2) //使用索引访问第三个
  4. grs.columName //通过列名访问
  5. }

七、流程控制方面

  1. testRunner.testCase //可以访问和操作项目中的所有对象
  2. testRunner.fail(....) testRunner.cancel,结束测试执行
  3. testRunner.gotoTestStepByname("Groovy Script") // goto 表示跳转到哪一步开始执行,会等待当前脚本执行完成再跳转到对应步骤执行
  4. testRunner.runTestStepByname("Groovy Script") //脚本会先去执行这个步骤,然后继续执行当前脚本
  5. context.myProperty="aaaa" //会在上下文中创建一个名为myProperty的属性,赋值为aaa

八、脚本返回值和引用

  1. return UUID.randomUUID() \\return 返回数据
  2. ${Groovy Script#result} \\引用
  3. def result = context.expand( '${Groovy Script#result}' ) \\引用

九、抄的两个实例之一----为所有RestTestRequestStep设置请求头(Cookie,session),以及编码

  1. import com.eviware.soapui.support.types.StringToStringMap
  2. def cookiesList = testRunner.testCase.getTestStepByName("登录").testRequest.response.responseHeaders["Set-Cookie"] //获得登陆后返回响应中的set-cookie
  3. log.info "cookiesList:" + cookiesList
  4. def cookieNew =""
  5. cookiesList.each{
  6. cookieNew = cookieNew+it.split(";")[0]+";"; //拆分得到 SESSION
  7. }
  8. log.info "Cookie:"+cookieNew
  9. def cookieMap = new StringToStringMap() //cookiemap
  10. cookieMap.put("Cookie",cookieNew) //添加到map
  11. //Pass cookie to all testSteps of the project
  12. //将cookieMap设置到项目中的所有RestTestRequestStep,顺带设置编码
  13. def testSuiteList = testRunner.testCase.testSuite.project.getTestSuiteList()
  14. def testCaseList
  15. def testStepList
  16. testSuiteList.each{
  17. testCaseList = it.getTestCaseList()
  18. testCaseList.each{
  19. //获得RestTestRequestStep类型的testStepList
  20. testStepList = it.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class)
  21. testStepList.each{
  22. if(it.name!="登录"){
  23. it.testRequest.setRequestHeaders(cookieMap)
  24. it.testRequest.setEncoding("UTF-8")
  25. }
  26. }
  27. }
  28. }
  29. log.info "==========Cookie:"+ cookieMap.get("Cookie");

十、抄的两个实例之二----数据库验证

  1. import com.eviware.soapui.support.types.StringToStringMap
  2. def Location= testRunner.testCase.getTestStepByName("新增一个教材册次").testRequest.response.responseHeaders["Location"]
  3. log.info "Location:" + Location[0]
  4. def uid = Location[0].split("/")[-1]
  5. testRunner.testCase.testSteps["Input"].setPropertyValue("uid",uid)
  6. log.info "uid:" + uid
  7. import groovy.sql.Sql
  8. //获取testSuite对象,以获取其中参数
  9. def DBProperties = testRunner.testCase.testSuite
  10. //获取数据库对象
  11. def sql = Sql.newInstance(DBProperties.getPropertyValue( "connection-url" ),DBProperties.getPropertyValue( "sysdb-user-name" ),
  12. DBProperties.getPropertyValue( "sysdb-password" ),DBProperties.getPropertyValue( "driver-class" ))
  13. def query = "Select * From inf_book_second Where inf_book_second.uid = '"+ uid +"'"
  14. def raw = sql.firstRow(query )
  15. log.info query
  16. def expect_name = testRunner.testCase.getTestStepByName( "Properties" ).getPropertyValue('name')
  17. log.info "expect_name: "+expect_name
  18. def actual_name = raw.name
  19. log.info "actual_name: "+actual_name
  20. //断言
  21. assert actual_name ==expect_name

soapui groovy脚本汇总的更多相关文章

  1. [SoapUI] Post请求Body里面限制特殊字符(&、%),Groovy脚本里特殊字符需要添加“\”转义($)。

    SoapUI的Post请求,在body里面不能包含(&.%),如果含有这些特殊字符,请求会报错:在添加的Groovy脚本里有些特殊字符需要使用“\”转义($),不然也会报错.

  2. soapUI参数中文乱码问题解决方法 (groovy脚本中文乱码)

    soapUI参数中文乱码问题解决方法 可能方案1: 字体不支持中文,将字体修改即可: file-preferences-editor settings-select font 修改字体,改成能显示中文 ...

  3. excel文件的groovy脚本在SoapUI中进行数据驱动测试

    SoapUI Pro具有从外部文件读取数据的功能,例如:excel,csv等.但SoapUI不提供从excel文件读取数据的功能.因此,为了从SoapUI中的excel文件中读取数据,我们需要在gro ...

  4. soapUI系列之—-03 Groovy脚本常用方法2

    ------Groovy脚本常用方法 1.解析Json数据脚本 //groovy读取json的方式很简单,re.body.businessinfo.c2rate读取c2rate对应的值 import ...

  5. soapUI系列之—-02 Groovy脚本常用方法

    ------Groovy脚本常用方法 1. 设置参数值:setPropertyValuea. 设置 project level property//set to project level prope ...

  6. 手把手教你接口自动化测试 – SoapUI & Groovy

    手把手教你接口自动化测试 – SoapUI & Groovy http://www.cnblogs.com/wade-xu/p/4236295.html 关键词:SoapUI接口测试,接口自动 ...

  7. 手把手教你接口自动化测试 – SoapUI & Groovy【转】

    手把手教你接口自动化测试 – SoapUI & Groovy Posted on 2015-01-21 09:38 WadeXu 阅读(12741) 评论(10) 编辑 收藏 手把手教你接口自 ...

  8. jenkins2 groovy脚本参考

    使用plugin生成groovy脚本,或者参考已有的groovy脚本. 文章来自:http://www.ciandcd.com文中的代码来自可以从github下载: https://github.co ...

  9. ODI 12c中使用Groovy脚本创建工程

    本文主要介绍在ODI中使用groovy创建工程,并添加一个表转换的映射.要创建groovy脚本,可以从ODI Studio的菜单:工具->Groovy->新脚本 打开一个编辑窗口.在执行下 ...

随机推荐

  1. git库初次下载

    1.右键Git Batch Here==>输入 git config --list 确认2.再次输入ssh-keygen -t rsa -C “修改后的邮箱” 3.回车多次 找到 生成序列目录 ...

  2. Linq to sql 之 ExecuteQuery 错误:指定的转换无效

    问题:通过dbContext.ExecuteQuery 得到数据并赋值给一个集合. 代码: public IEnumerable<LeaveCodeSum> GetLeavTotal(st ...

  3. wamp 安装redis扩展

    phpredis扩展下载地址  http://windows.php.net/downloads/pecl/snaps/redis/ 1.选择redis DLL文件扩展 phpinfo 查看VC版本 ...

  4. GreenDao-自定义SQL查询-拼接多个查询条件-AndroidStudio

    //获取本地Pad(离线工作票列表) public static List<WTDetailTableBean> getPadWTList(String token, String use ...

  5. oracle wm_concat() 返回空

    参考 https://www.cnblogs.com/zengweiming/archive/2013/11/20/3433642.html select wm_concat(to_char(str) ...

  6. tomcat启动时引用非JAVA_HOME的指定路径

    参考 https://jingyan.baidu.com/article/066074d62d371cc3c21cb0ec.html 先查看bin/catalina.bat 再查看bin/setcla ...

  7. 【Django】关于使用阿里的iconfont

    刚刚从看到课程里老师使用了阿里提供的矢量图标iconfont.cn 我记录一下基本步骤: 1.登录iconfont.cn,搜索图标 2.选中想要的icon点击添加入库,再从右上方点购物车,把icon添 ...

  8. hibench 对CDH5.13.1进行基准测试(测试项目hadoop\spark\)HDFS作HA高可靠性

    使用CDH 5.13.1部署了HADOOP集群之后,需要进行基准性能测试. 一.hibench 安装 1.安装位置要求. 因为是全量安装,其中有SPARK的测试(SPARK2.0). 安装位置在SPA ...

  9. jakson

    Java下常见的Json类库有Gson.JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的J ...

  10. XHXJ's LIS(数位DP)

    XHXJ's LIS http://acm.hdu.edu.cn/showproblem.php?pid=4352 Time Limit: 2000/1000 MS (Java/Others)     ...