SoapUI自动化资料整理

本文档整理了SoapUI自动化测试的相关资料,重点介绍了如何在TestSuite的SetUp Script中进行配置以实现Cases的参数化。示例中展示了当有两个测试用例CaseName1和CaseName2,它们的测试逻辑相同但输入数据不同时,如何通过SetUp Script进行差异化设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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> Property Expansion in soapUI: ${Search Request#Response#//ns1:Item[1]/n1:Author[1]/text()}   
  Examples: 
  response = context.expand('${GetDataPoints#Response) ---Json format
  response = context.expand('${GetDataPoints#Response#$.params[2].options[0].id}')     ---Json format
'.'表示当前json对象
  
  /**
  *<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


2> Where scope can be one of the following literal values: 
#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 

#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"

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

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

#[TestStep name]# - references a TestStep property 
Example: 
Property step:   context.expand('${Properties#variable}')
Groovy Step: context.expand('${getSql2#result}')
Request Step:   context.expand('${Request 1#Response}')


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


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 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
1> testRunner.runTestStepByName("GetBookByIdRequest_JSON")
2> testRunner.testCase

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 Get current test step:
 TestStep step = context.getCurrentStep()
2.3.2 Get the index of current step:
 in index = context.getCurrentStepIndex()
2.3.3 Get property:  
 context.getProperty(String testStep, String propertyName)
2.3.4 TextCase 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)

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

3. Get response of testStep:
3.1 Get the response of current testStep
1> response = messageExchange.response.responseContent
2> response = messageExchange.responseContent


3.2 Get the response of the other 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

import groovy.json.jsonSlurper
response = messageExchange.response.responseContent
slurper = new JsonSlurper()
json = slurper.parseText(response)
meta = json._meta.response_status


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


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
   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"]

   
7. 数据库连接
7.1 Script:
testLibrary: http://docs.groovy-lang.org/latest/html/gapi/groovy/sql/Sql.html

import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:netezza://host:5480/dbName;loginTimeout=60000","username","password","org.netezza.Driver")
sql.eachRow("select x, y from xxxxx "){
log.info("gromit likes ${it.x}")
}

7.2 SoapUI component
Sql Server connection as an example:
1> Copy the sqljdbc4.jar to the file path '..\SoapUI-5.2.1_free\bin\ext', then restart 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> test case -> Add Step -> JDBC Request
4> Configuration:
Driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
Connection String: jdbc:sqlserver://HOST:1433;databaseName=DB;user=USER;password=PWD

8. JsonSchema defination
   http://json-schema.org/documentation.html

9. JsonSchema validator
   相关jar包下载:http://download.youkuaiyun.com/my/uploads
   Example: http://rainy646556896.iteye.com/admin/blogs/2275259


10. XmlSchema validator   
Schema教程: http://www.w3school.com.cn/schema/
Example: http://blog.youkuaiyun.com/authorzhh/article/details/8930638
http://ufopw.iteye.com/blog/767249
   
11. External library(若需用到一些外部jar包,可以放到这个目录下面)
   External library path:  ".\ReadyAPI-1.4.1\bin\ext"


12. 如何在帮助文档中找到对应的类:
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
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])
}


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不一样:

[{
	"name": "CaseName1",
	"listjson": "listjson_demo_1",
	"columnsetjson": "columnsetjson_demo1",
	"ids": "DP003"
},
{
	"name": "CaseName2",
	"listjson": "listjson_demo_2",
	"columnsetjson": "columnsetjson_demo2",
	"ids": "DP005"
}]


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
 
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值