Friday, February 8, 2013

SOAPUI MockServices and Groovy Response

Suppose you have a request like this:


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <IdentifyCustomer>
         <WebIdentification>
            <Email>vernetto@yahoo.com</Email>
            <Password>ciao</Password>
         </WebIdentification>
      </IdentifyCustomer>
   </soapenv:Body>
</soapenv:Envelope>



and you must return this response whenever the email contains "@yahoo.com":

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <IdentifyCustomerResponse>
         <!--You have a CHOICE of the next 2 items at this level-->
         <IdentificationSuccessful>
            <MarketID>2</MarketID>
            <CustomerID>123456</CustomerID>
         </IdentificationSuccessful>
      </IdentifyCustomerResponse>
   </soapenv:Body>
</soapenv:Envelope>   


and this response whenever the email contains "@gmail.com":

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <IdentifyCustomerResponse>
         <IdentificationFailed>
            <ErrorCode>CUSTOMER_NOT_FOUND</ErrorCode>
            <ErrorDescription>we cannot find this customer</ErrorDescription>
         </IdentificationFailed>
      </IdentifyCustomerResponse>
   </soapenv:Body>
</soapenv:Envelope>


You can create a MockService and customize the MockResponse http://www.soapui.org/Getting-Started/mock-services/4-Customizing-a-MockResponse.html

this is the script:


def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = groovyUtils.getXmlHolder( mockRequest.requestContent ) 
def email = holder.getNodeValue("//Email")

if (email.contains("@yahoo.com")) {
 context.setProperty( "myresponse", "<IdentificationSuccessful><MarketID>2</MarketID><CustomerID>123456</CustomerID></IdentificationSuccessful>" )
}
else {
 context.setProperty( "myresponse", "<IdentificationFailed><ErrorCode>CUSTOMER_NOT_FOUND</ErrorCode><ErrorDescription>we cannot find this customer</ErrorDescription></IdentificationFailed>" )
}



and this the Groovy Response


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <IdentifyCustomerResponse>
  ${myresponse}
      </IdentifyCustomerResponse>
   </soapenv:Body>
</soapenv:Envelope>


No comments: