how to mock service using soapui

Download How to Mock Service Using SOAPUI

Post on 03-Jan-2016




0 download

Embed Size (px)




How to mock Service using SOAPUI??Transferring values from the request to the response:

This is straightforward scripting done at the MockResponse level; the script uses properties of the mockRequest object to get hold of the incoming request, extracts the desired values via XPath and then writes the created result to a requestContext property:def temp="IBM";def groovyUtils=new xml=new XmlSlurper().parseText(mockRequest.requestContent)xml.breadthFirst().each{ def v=it.toString() if("name"){ temp=it.text();"============================================="+it.text()); }}context.session=temp+' Munna'mockOperation.setDefaultResponse("R1");a. Created mock service as ContextResponse with script. Here will have single response, based on request will return response. From request will take name as a message will add with"Munna" string.

b. This is the response

c. Start the server for contextService and execute request. Find the output below:

How to mock Service using SOAPUI??Read the response from a database:

This one requires a bit more work as we need to set up and close a database connection which we can use in our scripts. This is best done in the MockService start script as follows;import groovy.sql.Sql//def mockService=mockRunner.mockServicedef sql=Sql.newInstance("HostName","username","password","databaseDriver");context.dbConnection=sqldef row=sql.firstRow("select * from table") "=================="+row.get("column1");context .responseMessage = row.get("column2");mockOperation.setDefaultResponse("R1");if(context.dbConnection!=null){ "Closing the connection"; context.dbConnection.close()}Aim of Script:Here response is whatever we are getting data from DB. If we want to specifically want specify any condition based on request we can add like where condition with request element value.** Connecting data base and selecting first row. From that row, based on column name we can specially get the value and set to the context.a. Created mock service for database example. Find the URL details for Service:

b. This is the response for the request

c. Now time to execute the request. Find the request execution

LOGGERS:Groovy log:Whatever loggers we are using in script, it will display in Groovy log window.

soapUI log:soapUI log for process.

http log: Here headers details and message details will display.

Error log: while running application, if we may face any problems we can verify errors in error log.

Memory log: memory details

Jetty log: whenever will start the mock service, we can identify event in jetty log.

How to mock Service using SOAPUI??Selecting a response based on the request

To mock services based on request we can give static response. Here whatever request will pass will get same response from SOAP UI of mock Service. Here I want to show that how we can create dynamic responses using SOAP UI.1. Selecting a response based on the requestThis script is specified at the MockOperation level and uses the script code to extract the input values from the incoming request. Based on some validations it returns the name of the MockResponse to return to the client. The script is as follows:Aim of Script:In request we have name property based name property we are returning different responses like R1, R2 and R3.* If name is "AA" then response R1,* Else if name is "BB" then response R2,* Else response is R3.def temp="XX";def groovyUtils=new xml=new XmlSlurper().parseText(mockRequest.requestContent)xml.breadthFirst().each{ def v=it.toString()"===============""==================="+it.text()); if("name"){ temp=it.text();"===================matching tag=========================="+it.text()); }}//"*temp**"+temp);if(temp=='AA'){"if R1"); mockOperation.setDefaultResponse("R1");}else if(temp=='BB'){"else if Response 1"); mockOperation.setDefaultResponse("R2");}else{"else Response 1"); mockOperation.setDefaultResponse("R3");}a. Create SOAP Project in SOAPUI

b. Import wsdl into the project

c. Here we can see operation is "doAction". Right click on request and create mock service.

d. Mock service name is given as MultipleResponses. Our aim to create multiple responses for single request. Click on operation and create responses like below.

e. Already I have created two responses, creating one more response (R3) for operation.

f. Responses R1, R2 and R3 are ready

g. Now step is to write script for to handle request. Click on operation and change dispatch to SCRIPT.

h. Copy that script whatever I have provided before creating SOAP project.

i. Change the target URL for request to MultipleResponse

j. Provide URL

k. Start the mock server for "MultipleResponses". l. This is my R1 response

m. Execute request

Streamlined service simulation

MockServices in soapUI gives you the unique ability to mimic Web services and create/run Functional and Load Tests against them even before they are implemented. Better yet, this allows you to eliminate the expense of building full-scale replicas of your production systems, as well as provide your customers access to your services without having to wait for them to be complete or available. In soapUI, you can create standards-compliant Mocks with virtually no effort on your part : just select a WSDL from your desired location and soapUI automatically generates the MockService and its methods for you. Then populate it with pre-defined responses for requests, customize responses any way you like, and define different responses for a given operation. Use the advanced scripting features to simulate any kind of desired behavior : fixed responses, random errors, dynamic results, and much more.1)MockService Scripting OverviewA quick recap of the MockService model in soapUI: A MockService contains an arbitrary number of MockOperations, which each mock some WSDL operation in the containing project. These MockOperations can mock operations in different WSDL services, so a single MockService can mock any number of WSDLs to any extent. Each MockOperation contains an arbitrary number of MockResponse messages, i.e. messages that are returned to the client when the MockOperation is invoked. Exactly which message to return is decided by the MockOperation dispatch method, for which several are available; sequence, random, script, etc.For the MockService itself there are number of scripting events available: Start and Stop scripts:these are useful for opening or closing shared objects (for example collections or database connections) which can be made accessible to scripts "further down" in the mock object hierarchy. OnRequest script:this is the main handler for simulating non-SOAP behavior (REST, etc); it is called before soapUI does any internal dispatching and has the possibility to return any kind of response to the client (thus bypassing the whole soapUI dispatch mechanism) AfterRequest script:primarily intended for custom logging and reporting functionality2)Mock Handler ObjectsA number of objects are commonly available in most scripts; here comes a quick overview with links to their corresponding javadoc: context:used for storing MockService-wide objects, for example database connections, security tokens, etc requestContext:used for storing Mock Request-wide objects, for example dynamic content to be inserted into the response message mockRequest:an object corresponding to the actual request made to the MockService. Through this object you can get hold of the incoming message, its headers, etc. Also the underlying HttpRequest and HttpResponse objects are available for "low-level" processing mockResult:an object encapsulating the result of the dispatched request, this is available in the MockService.afterRequest script. mockResponse/mockOperation:objects available at the corresponding levels for accessing the underlying configuration and functionality mockRunner:the object corresponding to the execution of the MockService; this gives you access to previous mock results, etcA company that decides to implement a Web API must make two critical decisions. First, what protocol will they use to exchange information between the client and the server. Rest and Soap are the most popular, but there are many other options including developing a JavaScript library that hides the web services interaction from the client programmer (this is what Google Maps does).The second decision is to decide what data format to use when returning information to the client. The most popular data formats are XML and JSON, but there are many other formats supported by big players such as YouTube, which supports the Atom data format. The following table provides a view of the protocols and formats supported by the 10 most popular Web APIs (data obtained from Formats

Google MapsJavaScriptXML, VML, JSON, KML


YouTubeGData, AtomGData, RSS

Amazon eCommerceREST, SOAPXML



Microsoft Virtual EarthJavaScriptKML, GeoRSS


Google SearchSOAPXML

Yahoo MapsREST, JavaScript, FlashXML

As part of a customer contract, over the past 6 weeks QualityLogics web services testing team utilized SoapUI to develop an automated functional conformance test for a REST API that provides account management services to a variety of related web sites. The 100 resource paths in the API all used http POST requests with an XML fragment contained in the body of the http message conveying the desired actions and/or respo