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 = "http://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:
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中進行相關配置,示例如下:

有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