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 March 1, 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

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

  1. 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
  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. Thank you for the article. Can you pls explain the diff on authorization types:
    1. NLTM
    2. Basic
    3. OAuth
    4. Spengo/Kerberos

    Reply
  4. 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

Leave a Comment