soapui总结资料收集


title: 【个人笔记-优化格式】soapui总结资料收集
tags: 新建,模板,小书匠
grammar_cjkRuby: true


[TOC]

简介

TestRunner:

a TestCaseRunner object, which is the entry-point to the SoapUI API for accessing project items,results, and so on.
context:
a TestCaseRunContext object holding context-related properties.
messageExchange:
当前交互 request/response 的 MessageExchange,可以用来直接访问 message content, HTTP Headers,Attachment 等对象:
http://www.soapui.org/apidocs/com/eviware/soapui/model/iface/MessageExchange.html
log: 一个标准的 Log4j Logger 对象

SoapUI官网:

https://www.soapui.org/
http://readyapi.smartbear.com/
http://readyapi.smartbear.com/structure/steps/script/groovy/start

API Document:

http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/teststeps/RestResponseMessageExchange.html
http://www.soapui.org/apidocs/com/eviware/soapui/model/testsuite/TestSuite.html
http://www.soapui.org/apidocs/com/eviware/soapui/model/testsuite/TestCaseRunner.html
http://www.soapui.org/apidocs/com/eviware/soapui/model/testsuite/TestStep.html
http://docs.groovy-lang.org/latest/html/gapi/
https://smartbear-cc.force.com/portal/KbHome?utm_source=doc_notif_popup&utm_medium=rapi&utm_campaign=Support

TestCase Memory Usage:

http://www.soapui.org/working-with-soapui/improving-memory-usage.html
By default, SoapUI automatically saves the entire request-response message exchange
for each request so it can be viewed by double-clicking the corresponding entry in
the TestCase log. Obviously this will fill up memory over time no matter how much
you have allocated, but fortunately there are ways to discard old results from memory if not needed.

1. 属性表达式Property Expansion

1.1 获取响应数据:

${Search Request#Response#//ns1:Item[1]/n1:Author[1]/text()}  

1.1.1获取json属性

response = context.expand('${GetDataPoints#Response)---Json format
response = context.expand('${GetDataPoints#Response#$.params[2].options[0].id}') ---Json format
'.'表示当前json对象

1.1.1获取XML属性

 /**
  *<Results>
  * <ResultSet fetchSize="128">
  * <Row rowNumber="1">
  * <ID>0Axxxxx</ID>
  * <aaaY>4</aaaY>
  * </Row>
  * </ResultSet>
  *</Results>
  */
  responseAsXml = context.expand( '${JDBC Request#ResponseAsXml')---Xml format
  responseAsXml = context.expand('${JDBC Request#ResponseAsXml#//Results[1]/ResultSet[1]/Row[1]/ID[1]}')  --Xml format

1.2 获取property属性值:

1.2.1 获取Project、TestSuite、TestCase中的属性值

#Project# - references a Project property(Reference properties across a particular SoapUI project) 
#TestSuite# - references a TestSuite property in the containing TestSuite 
#TestCase# - references a TestCase property in the containing TestCase
Example:  context.expand("${#Project#FilePath}")
 context.expand("${#TestSuite#FilePath}")
 context.expand("${#TestCase#FilePath}")

#MockService# - references a MockService property in the containing MockService 

1.2.2 获取全局属性值

#Global# - references a global property. Found in File>Preferences>Global Properties tab. Reference properties across all projects 
Example: Preferences -> Global Properties:    test = global variables
assert context.expand("${test}") == "global variables"

1.2.3 获取系统属性值

#System# - references a system property. Found in Help>System properties. 
Example: assert context.expand('${#System#file.encoding}') == 'GBK'

1.2.4 获取环境变量值

#Env# - references an environment variable 
Example: context.expand('${#Env#JAVA_HOME}')

1.2.5 获取TestStep中属性值

#[TestStep name]# - references a TestStep property 
Example: 
Property step 获取属性值
Property step:   context.expand('${Properties#variable}')
脚本step获取return的返回值
Groovy Step:     context.expand('${getSql2#result}')
请求step获取响应值
Request Step:   context.expand('${Request 1#Response}')

1.3 Dynamic Properties: 动态属性

${=(int)(Math.random()*1000)}
${=request.name}
${=request.operation.interface.project.name}
${=import java.text.SimpleDateFormat ; new SimpleDateFormat("YYYY-MM-DDT00:00:00").format(new Date())}

context.expand('${=request.name}')

Test library: http://www.soapui.org/apidocs/com/eviware/soapui/impl/rest/RestRequest.html

1.4 Nested Properties: 嵌套属性

testxml = "hello" 
testxpath = "//value[@id=${id}]/text()" 
id = "123" 
-> "${#testxml#${testxpath}}" evaluates to "hello" 

2. SoapUI自定义变量:

2.1 messageExchange:

testLibrary: http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/teststeps/RestResponseMessageExchange.html

2.1.1 获取响应Get response content:

 response = messageExchange.response.responseContent
 response = messageExchange.responseContent
 String response = messageExchange.getResponseContent()
 String response = messageExchange.getResponseContentAsXml() 

2.1.2 获取请求URL Get the request URL:

 String url = messageExchange.getEndpoint()

2.1.3 获取响应头 Get the request headers:

    HashMap map = messageExchange.getResponseHeaders()

2.1.4 获取响应状态码 Get http code:

 int status = messageExchange.getResponseStatusCode()

2.1.5 获取耗时 Get time taken:

 long time = messageExchange.getTimeTaken() 

2.2 testRunner:

com.eviware.soapui.impl.wsdl.panels.support.MockTestRunner
testLibarary: http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/panels/support/MockTestRunner.html

testRunner.testCase  //可以访问和操作项目中的所有对象
testRunner.fail(....)  testRunner.cancel,结束测试执行
testRunner.gotoTestStepByname("Groovy Script") // goto 表示跳转到哪一步开始执行,会等待当前脚本执行完成再跳转到对应步骤执行
testRunner.runTestStepByname("Groovy Script") //脚本会先去执行这个步骤,然后继续执行当前脚本

2.3 context:

com.eviware.soapui.impl.wsdl.panels.support.MockTestRunContext
testLibarary: http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/panels/support/MockTestRunContext.html

2.3.1 获取当前testStep,Get current test step:

TestStep step = context.getCurrentStep()

2.3.2 获取当前TestStep所在index Get the index of current step:

 in index = context.getCurrentStepIndex()

2.3.3 获取属性 Get property:

 context.getProperty(String testStep, String propertyName)

2.3.4 获取用例 TestCase

tc = context.getTestCase()

2.3.5 获取TestCaseRunner

tcr = context.getTestRunner()

2.3.6 context.expand('${#TestCase#expectValue}')

2.3.7 使用Via XPath expressions

def responseAsXml = context.expand( '${HTTP Request#ResponseAsXml#//table[4]/tr[2]/td[3]/table[1]/tr[1]/td[2]/span[4]/text()}')
log.info responseAsXml
xptah specs: http://www.w3school.com.cn/xpath/xpath_syntax.asp

2.3.8 其他方法 other methods:

 getProperties, getProperty, getPropertyNames, hasProperty, removeProperty, setProperty

2.4 log:

testLibarary: org.apache.log4j.Logger
log.info "Test information"

2.5 project:

http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/WsdlProject.html

1> project.name
2> project.getPropertyValue(name)
3> project.setPropertyValue(name, value)
4> project.testSuiteList.each{log.info it.name}
5> project.testSuites.each{key,value-> 
 log.info key     //case name
  }

2.6 testSuite: com.eviware.soapui.impl.wsdl.WsdlTestSuite

http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/WsdlTestSuite.html

1> testSuite.name
2> testSuite.getProject().getPropertyValue(name)
3> testSuite.getProject().setPropertyValue(key,value)
4> testSuite.getPropertyValue(name)
5> testSuite.setPropertyValue(name,value)
6> testSuite.testCaseList.each{log.info it.name}
7> testSuite.testCases.each{key,value-> 
 log.info key     //case name
  }
8> testSuite.getTestCaseByName(arg0)  

2.7 testCase: com.eviware.soapui.impl.wsdl.WsdlTestCasePro

http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/testcase/WsdlTestCase.html

1> testCase.name
2> testCase.getPropertyValue(name)
3> testCase.setPropertyValue(name, value)
4> testCase.testStepList.each{log.info it.name}
5> testCase.getTestSteps().each{key, value->
log.info key
}
6> testCase.getTestStepByName(arg0)
8> testCase.project
9> testCase.testSuite
10> testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class) 通过类型过滤查找得到 testSteps列表。

3. 获取响应Get response of testStep:

3.1 获取当前 testStep的响应

1> response = messageExchange.response.responseContent
2> response = messageExchange.responseContent

3.2 获取其他testStep的响应.

1> context.expand('${testStepNM#response}')
2> testRunner.testCase.testSteps["testStepNM"].testRequest.response.contentAsString

4. Json解析和构建

4.1 jsonSlurper解析

testLibarary: http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonSlurper.html

如json为:
        {"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}
] }
import groovy.json.jsonSlurper
response = messageExchange.response.responseContent
// response = testRunner.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString  
def slurper = new JsonSlurper()  
def re = slurper.parseText(response)  
//访问顶级元素,返回的是一个列表使用size 获得长度
re.calendar   re.calendar.size()
//访问元素模式  
re.calendar.calendar_id     re.calendar.calendar_id[index]
//另一种访问形式
re['calendar']['calendar_id'][index]
//查找过滤
re.calendar.calendar_id.find{it=='1706'}  //获得的结果是 calendar_id  1706
re.calendar.find{it.calendar_id=='1706'}  //获得的是calendar元素

4.2 JSONObject解析

def jsonMeta = net.sf.json.JSONSerializer.toJSON(messageExchange.responseContent); 
meta = jsonMeta.get("_meta").get("response_status")

4.3 json builder构建

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

5. xml解析

5.1 XmlParser

testLibarary: http://docs.groovy-lang.org/latest/html/api/groovy/util/XmlParser.html

def langs = new XmlParser().parse("languages.xml")  
def xml = ""
def langs2 = new XmlParser().parseText(xml) 
log.info langs.lang.attribute("text")  //注意与xmlSlurper的区别

5.2 XmlSlurper

testLibarary: http://docs.groovy-lang.org/latest/html/api/groovy/util/XmlSlurper.html

def langs = new XmlSlurper().parse("languages.xml")  
def xml = "*******"
def langs2 = new XmlSlurper().parseText(xml) 
log.info langs.lang.@text

Example 1:

xmlStr = '''
<Results>
  <ResultSet fetchSize="256">
 <Row rowNumber="1">
<DESCRIPTION>Information1</DESCRIPTION>
 </Row>
 <Row rowNumber="2">
<DESCRIPTION>Information2</DESCRIPTION>
 </Row>
 <Row rowNumber="3">
<DESCRIPTION>Information3</DESCRIPTION>
 </Row>
  </ResultSet>
</Results>
'''
def result = new XmlSlurper().parseText(xmlStr)
def rows = result.ResultSet.Row
log.info rows.DESCRIPTION.join(',')//output: Information1,Information2,Information3

示例:http://renjie120.iteye.com/blog/1504827

6. 常用method-testRunner

6.1 Get response:

testRunner.testCase.testSteps["ColumnSetsAllSummary"].testRequest.response.contentAsString 
context.expand('${Groovy2#result}')
context.expand('${Request 1#Response}')

6.2 Add propery:

testRunner.testCase.getTestStepByName("stepNM").addProperty("propertyNM")
testRunner.testCase.addProperty("propertyNM")
testRunner.testCase.testSuite.addProperty("propertyNM")

6.3 Set property value:

testRunner.testCase.getTestStepByName("stepNM").setPropertyValue("propertyNM","value")
testRunner.testCase.setPropertyValue("propertyNM","value")
testRunner.testCase.testSuite.setPropertyValue("propertyNM","value")

6.4 Delete property:

testRunner.testCase.getTestStepByName("stepNM").removeProperty("properNM")
testRunner.testCase.removeProperty("properNM"))
testRunner.testCase.testSuite.removeProperty("properNM")

6.5 Get properties:

HashMap map = testRunner.testCase.getTestStepByName("failedDataPoints").getProperties()

6.6 Get a property value:

testRunner.testCase.testSteps["Properties"].getPropertyValue("properNM")
testRunner.testCase.getTestStepByName("Properties").getPropertyValue("properNM")
testRunner.testCase.getPropertyValue("propertyNM")
testRunner.testCase.testSuite.getPropertyValue("propertyNM")

6.7 Get all property names:

testRunner.testCase.getTestStepByName("stepNM").getPropertyNames()

6.8 Get cookie:

testRunner.testCase.getTestStepByName("login").testRequest.response.responseHeaders["Set-Cookie"]

6.9 向下访问

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

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

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

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

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

6.12 获取响应体

myResponse=testRunner.testCase.getTestStepByName("新增一个空间").testRequest.response
myRequest=testRunner.testCase.getTestStepByName("新增一个空间").testRequest
可以替换使用:getTestRequest(),testSteps[testStepName],getResponse()等。

context.expand('${Groovy2#result}')
context.expand('${Request 1#Response}')
比较特殊的2个
获取响应作为String
myResponse.contentAsString 或者 myRequest.getResponseContentAsString()
获取响应作为Xml
myResponse.contentAsXml 或者myRequest.getResponseContentAsXml()

6.13 响应头和请求头

响应头:

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

请求头:

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

设置请求头

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

6.14 获取请求地址

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

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

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

6.16 获取全部用例并循环

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

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

 for(int i=0; i<testSuite.getTestCaseCount(); i++) {
     if (!testSuite.getTestCaseAt(i).isDisabled()) {
     if (!(testSuite.getTestCaseAt(i).getTestStepByName("stepName")).equals()){
   .....
         }
      }
   }

6.18 获取getTestSuiteCount()

testRunner.testCase.testSuite.project.getTestSuiteCount()

6.19 获取名称

部分元件只有Label和Name中的一个,测试一下就知道了。
    getLabel() 和getName()大多数情况是等价的
    a. 取test case的名称
    def tc = testRunner.testCase;
    log.info (tc.getLabel());
    b. 取test suite的名称
    def ts = testRunner.testCase.testSuite;
    log.info (ts.getLabel());
  getName()
   取project 名称
   def tp = testRunner.testCase.testSuite.project;
   log.info (tp.getName());

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

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

6.21 全局属性变量访问

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

6.22 脚本返回值和引用

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

7. 数据库连接

7.1 Script:

testLibrary: http://docs.groovy-lang.org/latest/html/gapi/groovy/sql/Sql.html

1、初始化
import groovy.sql.Sql
   sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words",
          "words", "org.gjt.mm.mysql.Driver")
2、查出所有行
   sql.eachRow("select * from word"){ row |
      println row.word_id + " " + row.spelling + " " + row.part_of_speech
   }
3、执行插入操作
wid = 999
spelling = "Nefarious"
pospeech = "Adjective"
sql.execute("insert into word (word_id, spelling, part_of_speech)
  values (${wid}, ${spelling}, ${pospeech})")
4、使用位置参数
val = sql.execute("select * from word where word_id = ?", [5])
5、更新
nid = 5
spelling = "Nefarious"
sql.executeUpdate("update word set word_id = ? where spelling = ?", [nid, spelling])
6、删除
sql.execute("delete from word where word_id = ?" , [5])
7、创建数据集
sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words",
         "words", "org.gjt.mm.mysql.Driver")
   words = sql.dataSet("word")
   words.each{ word |
    println word.word_id + " " + word.spelling
   }
   words.add(word_id:"9999", spelling:"clerisy", part_of_speech:"Noun")
8、查询结果集的访问
sql.eachRow("select * from word"){ grs |
  println "-1  = " + grs.getAt(-1) //使用索引访问最后一个
  println "2  = " + grs.getAt(2) //使用索引访问第三个
   grs.columName //通过列名访问
}

7.2 SoapUI component

Sql Server connection例子:
1> 复制sqljdbc4.jar 到目录'..\SoapUI-5.2.1_free\bin\ext', 然后重启soapui
2> Preferences -> JDBC Drivers,中查看设置

  jdbc:netezza://<HOST:127.0.0.1>:<PORT:12>/<DB>?user=<USER>&password=<PASSWORD>
  jdbc:sqlserver://<HOST:127.0.0.1>:<PORT:1433>;databaseName=<DB>;user=<USER>;password=<PASSWORD>

3>project>JDBC connections Configuration:

name:自定义
Driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
Connection String: jdbc:sqlserver://HOST:1433;databaseName=DB;user=USER;password=PWD

4> test case -> Add Step -> JDBC Request
driver的值 和上面的name一致

8. JsonSchema defination

http://json-schema.org/documentation.html

9. JsonSchema validator

相关jar包下载:http://download.csdn.net/my/uploads
Example: http://rainy646556896.iteye.com/admin/blogs/2275259

10. XmlSchema validator

Schema教程: http://www.w3school.com.cn/schema/
Example: http://blog.csdn.net/authorzhh/article/details/8930638
http://ufopw.iteye.com/blog/767249

11. 调用第三方包

11.1.调用第三方jar包

soapui可以调用第三方jar包/.class/.groovy文件;
打开soapui中lib目录(我的SoapUI-Pro-5.1.2.exe目录为C:\Program Files (x86)\SmartBear\SoapUI-Pro-5.1.2\lib),可以看到这里有很多jar文件。将第三方jar(java.jar/groovy.jar)包放进去,将以上三个脚本打成pub.jar放入,调用方法如下:
在testCase中新建一个Groovy Script,然后输入如下代码:
import pub.Text
def text = new Text()
text.writeFile("D:\1.log", "test")
执行完成后可以看到在d盘下建立了一个1.log文件,并写入test;

11.2.调用第三方.class文件

将得到的java.jar文件解压得到.class文件,将解压出来的文件夹及.class文件放到${soapui}/bin/scripts(我的SoapUI-Pro-5.1.2.exe目录为C:\Program Files (x86)\SmartBear\SoapUI-Pro-5.1.2\bin\scripts)目录下,调用方法和.groovy文件一致

11.3.调用第三方.groovy文件

将如上第三个.groovy脚本放在pub文件夹下,拷贝到${soapui}/bin/scripts(我的SoapUI-Pro-5.1.2.exe目录为C:\Program Files (x86)\SmartBear\SoapUI-Pro-5.1.2\bin\scripts)目录下,调用方法如下:

import pub.Text //如果这么写报错则改成import scripts.pub.Text
def text = new Text()
text.writeFile("D:\1.log", "test")

执行完成后可以看到在d盘下建立了一个1.log文件,并写入test;

11.4.再谈调用第三方jar包!

打开${soapui}/bin/ext(我的SoapUI-Pro-5.1.2.exe目录为C:\Program Files (x86)\SmartBear\SoapUI-Pro-5.1.2\bin\ext)目录有个readme.txt写着一行鸟语,大致意思是这个文件夹是存放外部jar文件的位置;
建议所有的外部文件均放在这个文件夹底下,像.class/.groovy尽量打成jar包放在ext文件夹下;之所以如此建议,是基于如下原因:
1.有些安装的soapui bin目录下并没有scripts文件夹(linux下安装或免费版soapui),当然你要手动去创建的话和安装自动生成并无差别;
2.在Linux下运行外部文件存在于scripts文件夹下的脚本会报错;
3.官方对于ext文件夹的描述为,soapui启动时首先加载外部jar包的地方;
4.groovy脚本打包时要注意,使用eclipse打包时会让我们勾选生成.class文件,不要勾选此选项,就使用原版的.groovy文件(不然运行时会报错);简单来说这个打包就跟你用压缩工具压缩然后改后缀为.jar效果是一样的。

12. 如何在帮助文档中找到对应的类:

注意:引入到其他IDE中开发,避免了这个问题
For example:
要获取到data step中所有的参数,Map props = testRunner.testCase.getTestStepByName("testData").getProperties(),但是
发现返回的key,value,value值不是我们想要的String类型的数据,我们可以一步一步找到对应的类:
1> 输出value的类型 log.info value.getClass().name,发现其类型为:com.eviware.soapui.impl.wsdl.support.XmlBeansPropertiesTestPropertyHolder$PropertiesStepProperty;
2> 帮助文档http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/panels/support/MockTestRunner.html,选择All Class,
搜索XmlBeansPropertiesTestPropertyHolder,点击进入,再找到Class PropertiesStepProperty,然后查看其API,可以看到有getValue()方法可以返回String类型
的值。API UIR: http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/support/XmlBeansPropertiesTestPropertyHolder.PropertiesStepProperty.html

13. 收费版script library配置:

Preferences -> Ready!API -> Script library
对应的配置在文件".Users\asun\soapui-settings.xml中,对应的node: id: "Script Library"

14. 免费版script library配置:

1> 个人代码打包成jar,放入路径\ext中
Netbeans打包Jar,参考: http://www.cnblogs.com/kunnet/archive/2013/02/19/2917471.html
2> 代码引入:
def groovyClasspath = context.expand( '${#Project#groovyClasspath}' )
String[] roots = [groovyClasspath]
engine = new GroovyScriptEngine(roots)
generateDataClass = engine.loadScriptByName('Test.groovy')
def gd = generateDataClass.newInstance()
log.info gd.testInfo()

15. Common used please see the GIT Hub:

https://github.com/adrcode

16. DataSource(groovy)

http://readyapi.smartbear.com/structure/sources/groovy/start
http://www.tuicool.com/articles/rqMV7jY
1新建一个DataSource步骤,选择Groovy方式
2.添加一个名为dataPointId的Properties
3.groovy编辑框中输入实现代码,result["dataPointId"]表示给属性dataPointId赋值

import groovy.json.JsonSlurper
def xresponse = testRunner.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString
def slurper = new JsonSlurper()
def re = slurper.parseText(xresponse)
def num = json.datapoints.id.size()
def i = testRunner.testCase.testSteps["DataSource"].currentRow
if(i < num)
{
result["dataPointId"]=String.valueOf(json.datapoints.id[i])
}

4.新建一个Property Transfer步骤,将DataSource的dataPointId传递给当前testCase的变量
5.新建 一个REST请求步骤,将得到的dataPointId去请求另一个接口
6.新建一个DataSource Loop步骤,使DataSource与Property Transfer步骤循环,这样就可以遍历数组中的每个数据了

17. TestSuite -> Setup Script

根据环境的不同,设置不同的变量:
def en = project.getPropertyValue("endpoint")
if(en =~ /.api.company.com./)
project.setPropertyValue("ApiKey", "111111")
else
project.setPropertyValue("ApiKey", "222222")

18. Setup Script: 依据环境选择相应的参数:

def url = testCase.getProject().getPropertyValue("endpoint")
if(url == "xxx")
testCase.setPropertyValue(name, value)

19. Environments:

def env = runner.testSuite.project.getActiveEnvironment().getName()
switch(env) {
case ['DEV', 'QA' , 'STG']:
testSuite.getProject().setPropertyValue("ApiKey", "xxxxx1")
break
case 'PROD':
testSuite.getProject().setPropertyValue("ApiKey", "xxxxx2")
break
}

20. Cases参数化---TestSuite的SetUp Script中进行相关配置,示例如下:

enter description here
enter description here

有2个case分别为CaseName1和CaseName2,测试逻辑完全一样,只是data input不一样:

1. [{  
2.     "name": "CaseName1",  
3.     "listjson": "listjson_demo_1",  
4.     "columnsetjson": "columnsetjson_demo1",  
5.     "ids": "DP003"  
6. },  
7. {  
8.     "name": "CaseName2",  
9.     "listjson": "listjson_demo_2",  
10.     "columnsetjson": "columnsetjson_demo2",  
11.     "ids": "DP005"  
12. }]  

TestSuite的SetUp中script如下:

    import groovy.json.JsonSlurper  
  
def testCaseParameters = '[{\"name\":\"CaseName1\",\"listjson\":\"listjson_demo_1\",\"columnsetjson\":\"columnsetjson_demo1\",\"ids\":\"DP003\"},{\"name\":\"CaseName2\",\"listjson\":\"listjson_demo_2\",\"columnsetjson\":\"columnsetjson_demo2\",\"ids\":\"DP005\"}]'  
runner.testSuite.setPropertyValue("tcParameters",testCaseParameters)  
  
def tcParameters = runner.testSuite.getPropertyValue("tcParameters")  
def jsonSlurper = new JsonSlurper()  
def parameters = jsonSlurper.parseText(tcParameters)  
  
 def loopNum = 0  
 parameters.each{  
     log.info "********* test case name:${it.name}"  
     runner.testSuite.getTestCaseAt(0).setName(it.name)  
     runner.testSuite.getTestCaseAt(0).getTestStepAt(0).setName(it.name)  
     runner.testSuite.getTestCaseAt(0).getTestStepAt(0).setPropertyValue("listjson", it.listjson)  
     runner.testSuite.getTestCaseAt(0).getTestStepAt(0).setPropertyValue("columnsetjson", it.columnsetjson)  
     log.info loopNum  
     if(loopNum++  < 1)  
         runner.testSuite.getTestCaseAt(0).run(null, false)  
 }  

常见问题:

1. "Can't get the Connection for specified properties;

com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. ClientConnectionId:ab000642-f920-49da-b0fa-c786f7fb12de"
sql windows authentication:
1> sqljdbc_auth.dll拷贝到/soapUI/bin目录下
2> Driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
ConnectionString: jdbc:sqlserver://host:1433;databaseName=dbName;integratedSecurity=true;
参考:https://social.technet.microsoft.com/Forums/zh-CN/d43cc053-fd2a-4e6f-a2fb-d1618bf871f5/integrated-security-with-the-microsoft-jdbc-driver-are-you-getting-the-error-failed-to-load-the?forum=sqldataaccess
官方: https://smartbear-cc.force.com/portal/KbArticleViewer?name=How-to-configure-SoapUI-Pro-JDBC-Datasource-with-SQL-Server-that-uses-windows-authentication

2. Encoding問題

Exected:
Alternative Strategies – Diversified Min Initial 50,000 and Above

Actually the response in soapUI is:
Alternative Strategies 鈥� Diversified Min Initial 50,000 and Above

Solution: 1> change the encoding for soapUI, Add the line ‘-Dfile.encoding=UTF8’ into the file \ReadyAPI-1.8.0\bin\ReadyAPI-1.8.0.vmoptions
2> 或者是,直接在request的header中配置參數Encoding=UTF-8

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容