------Groovy脚本常用方法
1.解析Json数据脚本
//groovy读取json的方式很简单,re.body.businessinfo.c2rate读取c2rate对应的值 import groovy.json.JsonSlurper def xresponse = testRunner.testCase.testSteps["Request"].testRequest.response.contentAsString def slurper = new JsonSlurper() def re = slurper.parseText(xresponse) def num=re.body.businessinfo.size() log.info(re.body.businessinfo.c2rate)
例:Json格式
{
"body":{
"businessinfo":{
"c1rate":"0.00",
"c2rate":"12.00",
"c4rate":"21.00",
"c5rate":"0.00",
"c6rate":"0.00",
"c8rate":"0.00",
"d1rate":"0.00",
"d2rate":"0.00",
"riskcode":"0355",
"ruleid":"R32000213878_11-0"
}
},
"head":{
"error_code":"0000",
"error_message":"成功",
"request_type":"???",
"response_code":"0"
}
}
2.获取reponse
//Get response def groovyUtils = new GroovyUtils( context ) def holder = groovyUtils.getXmlHolder('inquire#Response') //Parse return value def data = holder.getNodeValue("//return") log.info(data)
3. 导入需要用到的方法和脚本:例如MD5方法、groovy.json.JsonSlurper方法
例如:import groovy.json.JsonSlurper //导入groovy.json包中的JsonSlurper方法
4. 调用 Groovy,java 的jar包的方法
import pub.Text // 调用 Groovy 的jar包中方法, //此包必须与jar包中的包名一致 def text = new Text() text.writeFile("D:\1.log", "test")
操作方法:选中工程->Export-> JAR
这里打jar包时候要注意
1)WebContentMETA-INFMANIFEST.MF 这个文件打到jar包中去(这个文件描述了该Jar文件的很多信息)
2)要打的是class文件,即要选择Export generated class files and resources
5. 使用Groovy脚本执行接口请求
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext CURRENT_TESTCASE = testRunner.testCase TEST_SUITE = CURRENT_TESTCASE.parent def testStep = TEST_SUITE.getTestCaseByName('TestSuite').getTestStepByName('login') def testStepContext = new WsdlTestRunContext(testStep) def result = testStep.run(testRunner, testStepContext) log.info result.responseContent
调用另一个TestSuite中的teststep脚本如下:
def testproject = testRunner.testCase.testSuite.project
def testcase = testproject.testSuites['PublicCase'].testCases['TestCase1']
testcase.testSteps["CreateService1"].run(testRunner, context)
调用本TestSuite中的TestStep脚本如下:
testRunner.runTestStepByName("Login")
testRunner.runTestStepByName("CreateAPI1-Scenario2")
6. 步骤跳转脚本
testRunner.gotoStepByName("Step2") 跳转到指定步骤
testRunner.runTestStepByName("Step2") 运行指定步骤或脚本
7. 得到32位的UUID
import java.util.UUID
//得到32位的UUID //格式为:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12) def uuids = UUID.randomUUID().toString().toLowerCase() //得到去除横线的UUID def uuids = UUID.randomUUID().toString().replace("-", "").toLowerCase();
8. 获取cookie并添加到对应的请求中
import com.eviware.soapui.support.types.StringToStringMap def cookiesList = testRunner.testCase.getTestStepByName("login").testRequest.response.responseHeaders["Set-Cookie"] log.info cookiesList //Get the cookie String cookieNew = cookiesList.get(0) log.info "cookie : "+cookieNew //Put cookie to a StringMap def cookieMap = new StringToStringMap() cookieMap.put("Cookie",cookieNew) testRunner.testCase.getTestStepByName("filter").testRequest.setRequestHeaders(cookieMap);
其他参考资料: