How to Create Mock Service and Dynamic Response in SoapUI

In this tutorial, we will cover all about mock services. You will learn:

  • What is a mock service and why is it required?
  • How to create a mock service in SOAPUI?
  • What is mock operation and a dynamic mock response?
  • Understanding mock operation and dispatch methods with an example.
  • Scripting for Mock Response.

Mock Service:

Mocking a web service will help simulate a response to the request of a web service. It is a very effective tool for testing web services offline while building and evaluating them.

SoapUI Mock Service

Recommended read => 15+ Best SoapUI tutorials

The following are the steps in SOAPUI to create a project using web service WSDL and create a mock service of it.

For simplicity, I have used a sample WSDL in this tutorial:

#1) Create a soap project using the following WSDL:
http://www.webservicex.com/globalweather.asmx

(Note: Click on any image for enlarged view)

new-soapui-project

#2) Select ‘Generate MockService’ option by right-clicking on the project name.

generate-mock-service-option

generate-mock-service-option-1

#3) In MockService dialog box, options are available to change the port number and host name.

change-the-port-number-and-host-name

#4) Default response is created in the Mock Service.

default-response

#5) Start mock service.

start-mock-service

#6) Open the WSDL service in a browser.

open-the-wsdl-service

#7) WSDL of mock service will look like below in the browser:

wsdl-of-mock-service

#8) Copy the WSDL service URL and use it as the New EndPoint to send a request to the mock service.

new-end-point

new-end-point-1


#9) Submit Request to the newly added endpoint to receive a response from the Mock Service.

Mock Operation and Dynamic mock responses:

Once the request is received by a mock service, it will transfer it to the mock operation. Mock operation then selects the correct response from the list of responses and delivers it back to the web service.

1) We can add one more mock response and set a dynamic response based on the request/query or send a response either in sequence or randomly.

2) To add a new mock response, right click on the mock operation and select New Mock Response.

new-mock-response

3) Now in New Mock Response2, you can create soap fault response, if required.

soap-fault-response

4) Double clicking on the mock operation will open configuration panel which provides ways to set dynamic responses

set-dynamic-responses

Understanding Dispatch Methods:

In Configuration panel, by selecting the dispatch method we can set a dynamic response

Let’s see various dispatch methods:

SCRIPT: Using script we can set a dynamic response based on the contents of a request.

See the following example:

set-dynamic-response

In the Script method, use a Groovy script to read the request contents and extract the value of a specific node. See the following script example where the result response changes depending on the input request value.

import javax.xml.xpath.*
import groovy.xml.StreamingMarkupBuilder
import groovy.lang.Binding;
import groovy.lang.Script;
def util = new com.eviware.soapui.support.GroovyUtils( context )
def xml = new XmlSlurper().parseText(mockRequest.requestContent) 
def country = xml.Body.GetCitiesByCountry.CountryName
def str = country.toString()
log.info str
def len = str.size()
log.info len
if(len > 1 ) 
{
 context.ResultResponse = "Response1"
 log.info "r1"
}
else if(len <= 1)
{ 
 context.ResultResponse="InvalidMockResponse 2"
 log.info "r2"
}

SEQUENCE: This is a simple way of sending responses. Responses will be sent in a sequence i.e. first query first response, next query next response, etc.

QUERY_MATCH:  Query can be a little complex dispatch method. In this method, the response is based on the query result.

In the configuration panel, we can list one or more queries on the left and on the right panel we can specify the query (XPATH) and expected value. If the query matches the expected values then the selected response will be dispatched. Otherwise, the default response will be returned.

query_match

XPATH: This is almost similar to QUERY_MATCH but is not as powerful. It sends a response if XPATH matches.

RANDOM: This is one more simple way of dispatching responses; it just picks up any response in a random manner and dispatches right away.

Scripting for Mock Response:

Scripting is the most versatile and complicated option. But scripting provides a way to change the mock response contents, headers, attachments while sending it to the client. It also allows you to simulate valid or Invalid HTTP responses. Each mock response can have its own script for creating dynamic contents in the response message.

The script inspector at the bottom of the mock response editor is shown below:

the-script-inspector

Script example:

import javax.xml.xpath.*
import groovy.xml.StreamingMarkupBuilder
import groovy.lang.Binding;
import groovy.lang.Script;
def util = new com.eviware.soapui.support.GroovyUtils( context )
def xml = new XmlSlurper().parseText(mockRequest.requestContent)
def country = xml.Body.GetCitiesByCountry.CountryName
def str = country.toString()
log.info str
if(str == 'India' || str == 'INDIA')
{
context.CaptialCity = "Delhi"
}
else if(str == 'UK' || str == 'Uk')
{
context.CaptialCity = "London"
}

In the above example, the script simply sets the value of property ‘CaptialCity’ in the response of current context.

We can use a variety of ways to create the dynamic contents of property like querying a database or reading an external file, etc.

Conclusion:

Mock Services is one of the most powerful features of SOAPUI. Mock Service exposes a number of mock operations which in turn can contain an arbitrary number of mock responses. These responses will provide a tangible way to assess how the web service will actually work, how users will respond to it and use the application.

Dynamic mock responses in SOAPUI make it super useful in test automation.

With some extra scripting efforts, you can create Automated Test Steps which will surely increase the quality of testing as well as reduce testing time in development phases of any web application.

Hope this tutorial on creating mock service and producing dynamic response was helpful. Feel free to add your queries in below comments.




Recommended reading

5 comments ↓

#1 Liviu

Hi,

You have a bug in the script/example. The object that you refer is called CapitalCity and in your script it is CaptialCity (inverted “I” and “T”).

#2 Liviu

Except that, there is a nice tutorial that can be helpful for someone that needs this approach.

#3 Kishorebabu Muppalla

Thanq for the Tutorial, I am searching for this from long time. It helps me in creating mock services for my project.

#4 dheepika baskaran

Thank you for the article. Can you pls explain the diff on authorization types:
1. NLTM
2. Basic
3. OAuth
4. Spengo/Kerberos

#5 Maxim

Hey there!
Do you know how to edit mock response in OnRequest Script? I need to delete first character in my request.
I try to do this, but it doesn’t work. Do you know any solution?

My code:

def mockRequestContent
try {
mockRequestContent = mockRequest.getRequestContent()
mockRequestContent = replace(mockRequestContent) //method which returns mockRequestContent.substring(1)
mockRequest.setRequestContent(mockRequestContent)
log.info(mockRequestContent)
} catch (Exception e) {
log.info(e)
}

Leave a Comment