不廢話了直接上代碼
[TOC]
一、一些內部元件的訪問
testRunner.testCase開頭
1、向下訪問
testRunner.testCase.testSteps[testStepName]
testRunner.testCase.getTestStepByName("新增一個空間")
2、向上訪問,用于訪問同一項目中的其他testSuites 和 testCase下的元素
testRunner.testCase.testSuite.project.testSuites[testSuiteName].testCases[testCaseName].testSteps[testStepName]
3、幾乎所有元件都有get 和set屬性的方法
setPropertyValue getPropertyValue
//在下面的4,5,6點中,幾乎所有的屬性值都可以和對應的get方法互相替換等價
4、獲取響應體
myResponse=testRunner.testCase.getTestStepByName("新增一個空間").testRequest.response
myRequest=testRunner.testCase.getTestStepByName("新增一個空間").testRequest
可以替換使用:getTestRequest(),testSteps[testStepName],getResponse()等。
比較特殊的2個
獲取響應作為String
myResponse.contentAsString 或者 myRequest.getResponseContentAsString()
獲取響應作為Xml
myResponse.contentAsXml 或者myRequest.getResponseContentAsXml()
5、響應頭和請求頭
響應頭:
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、獲取請求地址
testRunner.testCase.getTestStepByName("查詢空間詳情").testRequest.path
7、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
8、獲取全部用例并循環(huán)
def testCaseList = testRunner.testCase.testSuite.getTestCaseList()
testCaseList.each{
if(it.testSteps["Input"])
it.testSteps["Input"].setPropertyValue("spaceid",uid)
}
9、相對的獲取用例數(shù),getTestCaseCount()
for(int i=0; i<testSuite.getTestCaseCount(); i++) {
if (!testSuite.getTestCaseAt(i).isDisabled()) {
if (!(testSuite.getTestCaseAt(i).getTestStepByName("stepName")).equals()){
.....
}
}
}
10、獲取getTestSuiteCount()
testRunner.testCase.testSuite.project.getTestSuiteCount()
11、獲取名稱
部分元件只有Label和Name中的一個,測試一下就知道了。
getLabel() 和getName()大多數(shù)情況是等價的
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());
12、在斷言中需要使用用例對象的話
messageExchange.modelItem.testCase.testSteps["Properties"].getPropertyValue("userId")
13、全局屬性變量訪問
對于項目中的屬性可分為這么幾個級別Global, Project,TestSuite, TestCase
即全局變量、項目級別、用例集級別、單個用例級別
要獲得如項目級別的屬性變量的話,可以用以下方法
def time_num=context.expand('${#Project#time_num}') //##號內為定義哪個級別的屬性變量,后面為屬性名
二、json操作
1、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
2、json 解析
如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
def xresponse = testRunner.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString
def slurper = new JsonSlurper()
def re = slurper.parseText(xresponse)
//訪問頂級元素,返回的是一個列表使用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元素
三、XML操作(解析)
ef groovyUtils = new com.eviware.soapui.support.GroovyUtils(context )
//獲取上下文對象,轉化成groovyUtils對象
defwsdlResponse=testRunner.testCase.testSteps["發(fā)貼"].getTestRequest().getResponseContentAsXml()
log.info("wsdlResponse==="+wsdlResponse)
//獲取指定步驟的返回信息并轉化成xml
holder = groovyUtils.getXmlHolder(wsdlResponse)
//獲取指定節(jié)點的值
defmessage=holder.getNodeValue("http://ns1:Response[1]/ns1:response[1]/ns1:e[1]/ns1:message[1]")
log.info("獲得節(jié)點對應的值是"+message)
deffandom_creator_sn=holder.getNodeValue("http://ns1:fandom_creator_sn")
log.info("獲得節(jié)點對應的值是"+fandom_creator_sn)
四、文件操作
直接百度groovy文件操作就好了,用得少不收集了
五、各級別的集合操作
1、TestSteps的操作
testRunner.testCase.testSuite.project.testSuites["互動空間測試用例"].testCases["空間管理測試"].testSteps
=getTestSteps()。都是獲取用例下的testStep列表,返回的是 key=object 形式的字典map
getTestStepList() 獲取用例下的testStep列表,純列表
getTestStepCount() 獲取數(shù)量
getTestStepAt(int) getTestStepById(java.util.UUID) 通過位置和UUID 查找step
getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class) 通過類型過濾查找得到 testSteps列表。
2、testCases操作
testRunner.testCase.testSuite.project.testSuites["互動空間測試用例"].testCases=getTestCases()
返回的是 key=object 形式的字典map
getTestCaseList(), 獲取的列表,純列表
getTestCaseCount(), 獲取數(shù)量
getTestCaseAt(int), getTestCaseById(java.util.UUID) 通過位置和UUID
3、testSuites操作
testRunner.testCase.testSuite.project.testSuites=getTestSuites()
返回的是 key=object 形式的字典map
getTestSuiteList(),獲取的列表,純列表
getTestSuiteCount() 獲取數(shù)量
,getTestSuiteAt(int), getTestSuiteById(java.util.UUID) 通過位置和UUID
4、返回是list時操作
testCaseList=testRunner.testCase.testSuite.project.testSuites["互動空間測試用例"].getTestCaseList()
log.info testCaseList[0] //使用 index訪問
//each循環(huán)
testCaseList.each{
it.xxxxx
}
5、返回是map時操作
testStepsMap=testRunner.testCase.testSuite.project.testSuites["互動空間測試用例"].testCases["空間管理測試"].testSteps
//使用名稱key訪問
log.info testStepsMap["新增一個空間"]
log.info testStepsMap.get("新增一個空間")
//遍歷 使用默認閉包it
testStepsMap.each{
log.info it.key+" "+it.value
}
//使用自定義閉包名稱遍歷
testStepsMap.each{myp->
log.info myp.key+" "+myp.value
}
六、數(shù)據(jù)庫操作
1、普通的jdbc編程
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample1 {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/words",
"words", "words");
stmt = con.createStatement();
rs = stmt.executeQuery("select * from word");
while (rs.next()) {
System.out.println("word id: " + rs.getLong(1) +
" spelling: " + rs.getString(2) +
" part of speech: " + rs.getString(3));
}
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}finally{
try{rs.close();}catch(Exception e){}
try{stmt.close();}catch(Exception e){}
try{con.close();}catch(Exception e){}
}
}
}
2、grrovy sql
import groovy.sql.Sql
sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words",
"words", "org.gjt.mm.mysql.Driver")
查出所有行
sql.eachRow("select * from word"){ row |
println row.word_id + " " + row.spelling + " " + row.part_of_speech
}
執(zhí)行插入操作
wid = 999
spelling = "Nefarious"
pospeech = "Adjective"
sql.execute("insert into word (word_id, spelling, part_of_speech)
values (${wid}, ${spelling}, ${pospeech})")
使用位置參數(shù)
val = sql.execute("select * from word where word_id = ?", [5])
更新
nid = 5
spelling = "Nefarious"
sql.executeUpdate("update word set word_id = ? where spelling = ?", [nid, spelling])
刪除
sql.execute("delete from word where word_id = ?" , [5])
創(chuàng)建數(shù)據(jù)集
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")
查詢結果集的訪問
sql.eachRow("select * from word"){ grs |
println "-1 = " + grs.getAt(-1) //使用索引訪問最后一個
println "2 = " + grs.getAt(2) //使用索引訪問第三個
grs.columName //通過列名訪問
}
七、流程控制方面
testRunner.testCase //可以訪問和操作項目中的所有對象
testRunner.fail(....) testRunner.cancel,結束測試執(zhí)行
testRunner.gotoTestStepByname("Groovy Script") // goto 表示跳轉到哪一步開始執(zhí)行,會等待當前腳本執(zhí)行完成再跳轉到對應步驟執(zhí)行
testRunner.runTestStepByname("Groovy Script") //腳本會先去執(zhí)行這個步驟,然后繼續(xù)執(zhí)行當前腳本
context.myProperty="aaaa" //會在上下文中創(chuàng)建一個名為myProperty的屬性,賦值為aaa
八、腳本返回值和引用
return UUID.randomUUID() \\return 返回數(shù)據(jù)
${Groovy Script#result} \\引用
def result = context.expand( '${Groovy Script#result}' ) \\引用
九、抄的兩個實例之一----為所有RestTestRequestStep設置請求頭(Cookie,session),以及編碼
import com.eviware.soapui.support.types.StringToStringMap
def cookiesList = testRunner.testCase.getTestStepByName("登錄").testRequest.response.responseHeaders["Set-Cookie"] //獲得登陸后返回響應中的set-cookie
log.info "cookiesList:" + cookiesList
def cookieNew =""
cookiesList.each{
cookieNew = cookieNew+it.split(";")[0]+";"; //拆分得到 SESSION
}
log.info "Cookie:"+cookieNew
def cookieMap = new StringToStringMap() //cookiemap
cookieMap.put("Cookie",cookieNew) //添加到map
//Pass cookie to all testSteps of the project
//將cookieMap設置到項目中的所有RestTestRequestStep,順帶設置編碼
def testSuiteList = testRunner.testCase.testSuite.project.getTestSuiteList()
def testCaseList
def testStepList
testSuiteList.each{
testCaseList = it.getTestCaseList()
testCaseList.each{
//獲得RestTestRequestStep類型的testStepList
testStepList = it.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class)
testStepList.each{
if(it.name!="登錄"){
it.testRequest.setRequestHeaders(cookieMap)
it.testRequest.setEncoding("UTF-8")
}
}
}
}
log.info "==========Cookie:"+ cookieMap.get("Cookie");
十、抄的兩個實例之二----數(shù)據(jù)庫驗證
import com.eviware.soapui.support.types.StringToStringMap
def Location= testRunner.testCase.getTestStepByName("新增一個教材冊次").testRequest.response.responseHeaders["Location"]
log.info "Location:" + Location[0]
def uid = Location[0].split("/")[-1]
testRunner.testCase.testSteps["Input"].setPropertyValue("uid",uid)
log.info "uid:" + uid
import groovy.sql.Sql
//獲取testSuite對象,以獲取其中參數(shù)
def DBProperties = testRunner.testCase.testSuite
//獲取數(shù)據(jù)庫對象
def sql = Sql.newInstance(DBProperties.getPropertyValue( "connection-url" ),DBProperties.getPropertyValue( "sysdb-user-name" ),
DBProperties.getPropertyValue( "sysdb-password" ),DBProperties.getPropertyValue( "driver-class" ))
def query = "Select * From inf_book_second Where inf_book_second.uid = '"+ uid +"'"
def raw = sql.firstRow(query )
log.info query
def expect_name = testRunner.testCase.getTestStepByName( "Properties" ).getPropertyValue('name')
log.info "expect_name: "+expect_name
def actual_name = raw.name
log.info "actual_name: "+actual_name
//斷言
assert actual_name ==expect_name