How to Create Mock Service and Dynamic Response in SoapUI

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated November 21, 2024

In this tutorial, you will get all the relevant information about mock services. You will learn the following in detail:

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

SoapUI Mock Service

 

Recommended read => 15+ Best SoapUI tutorials

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.

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 an 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 the one 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 Operations and Dynamic Mock Responses:

Once the request is received by the mock service, they 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 a soap fault response if required.

soap-fault-response

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

set-dynamic-responses

Understanding Dispatch Methods:

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

Please see various dispatch methods:

SCRIPT: Using a 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 content 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. However, scripting provides a way to change the mock response content, headers, and 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 content 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.

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

Conclusion:

Mock Services is surely 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 work, how users will respond to it and use the application.

Dynamic mock responses in SOAPUI make it extremely 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 services and producing dynamic responses was helpful. Feel free to add your queries in the comments section below. We would love to hear from you. 

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • How to Create and Execute

    This is the 4th tutorial of this SoapUI training series.  Here, you will learn how to create and execute your first SoapUI project using WSDL.  In the previous SoapUI tutorial, we discussed the SoapUI and SoapUI Pro installations.  You will learn Creating SOAP project- adding WSDL during creation or after…

  • soap vs rest services

    This tutorial talks in detail about SOAP (Simple Object Access Protocol) and REST (Representation State Transfer) based services and their advantages. Let's get started. In an earlier tutorial, we discussed the features of SoapUI Pro and briefly touched upon SOAP vs REST web services.  => Click here for the complete…

  • Top Incident Response Service provider

    Comprehensive Review and Comparison of the Best Incident Response Services to help you select an IR Service Provider for Reducing the Damage from Cyber Attacks: Incident Response is the process that is used to manage the consequences of cyber-attacks and security breaches. Incident Response team can also be called an…

  • soapui tutorials

    In this article, we have compiled a list of Soap UI Tutorials for the benefit of our readers. Let's get started. STH is coming up with another testing tool tutorial. You know how detailed and useful these tutorials are. The tools are SoapUI and SoapUI Pro. We suggest that our…

  • 4 Important Features of SoapUI Pro for Pro Audience – SoapUI Tutorial #12

    In this article, we will look at the 4 important features of SoapUI Pro for Pro Audience. Let's get started. SoapUI comes in two versions - Open Source Free (SoapUI) and SoapUI Pro (now SoapUI NG pro). So far we were discussing common automation concepts and functional testing basics such…

  • SoapUI and SoapUI Pro installation guide

    In this article, we will learn about the SoapUI download and Installation process. Let's get started.  In this tutorial, we will learn how to install SoapUI and SoapUI Pro with a trial key. We will also see a few major differences between SoapUI and SoapUI Pro and their plugins/add-ons at…

  • Properties in SoapUI

    In this tutorial, you will see how to use properties in SoapUI Groovy Script. Let's get started.  Properties are the central repository to store our information temporarily. They can contain login information like username and password, session data like session id, page context, header information and so on. This is…

  • soapui tutorial 15

    This tutorial is a Quick SoapUI Guide to store request and response data in a file. We will learn how to store the responses in a file for future reference.  This is the last tutorial in our SoapUI free training series. Click on this link for all the previous tutorials…


7 thoughts on “How to Create Mock Service and Dynamic Response in SoapUI”

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

    Reply
  2. 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)
    }

    Reply
  3. 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”).

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

    Reply
  5. Hi,
    I was using soap UI for mock service and war file generations.

    I’m able to generate a war file but after deployment in tomcat.

    when my service is running successfully in tomcat, I used soap UI to test the service.

    During which I’m getting below error/

    SoapUI MockServices Log for project [nb-workorder]

    Can you please assist me.

    Reply

Leave a Comment