Monday, January 16, 2012

Using Groovy scripts to select Dispatch actions in soapUI



You can use the power of Groovy for selecting MockResponses in soapUI
If your request is of the format :-
<ns1:foo>
  <ns3:data>
    <ns3:CustomerNumber>1234</ns3:CustomerNumber>
  </ns3:data>
</ns1:foo>








You can use the following script :-


def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def req = new XmlSlurper().parseText(mockRequest.requestContent)
log.info "Customer #${req.foo.data.CustomerNumber}"
context.result = req.foo.data.CustomerNumber


 

Here we are using mockRequest.requestContent to get the request soap envelope. We then use the XmlSlurper to parse this. XmlSlurper does not care about namespaces and it can parse XML into a document tree that may be traversed similar to XPath expressions. Doc : http://groovy.codehaus.org/api/groovy/util/XmlSlurper.html

context.result ensures that the MockResponse whose name =CustomerNumber (in this case 1234) is selected as a response.


log.info is for logging and can be tested in the “script log” tab below when you send a request


<SCRIPT LOG PIC>


Other variables that can be used are : mockOperation to select responses based on operation, requestContext and context.


You can have fancy scripts which contain if statements, connect to database, files, inlist etc whatever Groovy supports!


You may also pass back calculations by parsing parameters from request and converting them:-


Sample Response


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ=http://example.org/math/>
   <soapenv:Header/>
   <soapenv:Body>
      <typ:AddResponse>
         <result>${result}</result>
      </typ:AddResponse>
   </soapenv:Body>
</soapenv:Envelope>



Script


def request = new XmlSlurper().parseText(mockRequest.requestContent)
def a = request.Body.Add.x.toDouble()
def b = request.Body.Add.y.toDouble()
context.result = a + b


You can use XmlHolder as well if you care for namespaces:-


Request


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
   <soapenv:Body>
      <tem:RunScript>
         <!--Optional:-->
         <tem:optionObject>
            <tem:EntityID>5</tem:EntityID>
            <tem:Facility>98</tem:Facility>
              <Forms>
               <FormObject....


Script


def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = groovyUtils.getXmlHolder( mockRequest.requestContent ) 
holder.declareNamespace( 'tem', 'http://tempuri.org/')
context.Facility = holder.getNodeValue( "//tem:Facility")
context.EntityID = holder.getNodeValue( "//tem:EntityID")

But in this case you will have to explicitly declare namespaces.

No comments:

Post a Comment

Thank you for your feedback