Tutorial on How to create REST Web-Service Mocking Using soapUI
For Creating a REST Web-Service Mock Project Using soapUI 4.5.1
***Steps
for Creating Rest Web-Service Mock project***
(1)
Open soapUI with Empty workspace as below.
(2)
Select New soapUI project
option from soapUI File menu.
(3) Import the wadl file in soapUI like below:-
Note :-
Check mark in Creates a TestSuite for the imported WSDL and WADL will
default
create request for the available services.
application WADL File contents:-
<?xml version="1.0"
encoding="UTF-8" standalone="yes"?>
<application
xmlns="http://research.sun.com/wadl/2006/10">
<doc
xmlns:jersey="http://jersey.dev.java.net/"
jersey:generatedBy="Jersey: 1.4 09/11/2010 10:41 PM"/>
<resources
base="http://localhost:9070/Rest-Sample/rest/">
<resource path="HelloExample">
<method name="GET" id="sayPlainTextHello">
<response>
<representation
mediaType="text/plain"/>
</response>
</method>
<method name="GET" id="sayXMLHello">
<response>
<representation
mediaType="text/xml"/>
</response>
</method>
<method name="GET" id="sayHtmlHello">
<response>
<representation
mediaType="text/html"/>
</response>
</method>
<method name="GET" id="sayJSONHello">
<response>
<representation
mediaType="application/json"/>
</response>
</method>
</resource>
</resources>
</application>
(4)
Click on OK will display the
below dialog box:-
Note: - Select Single TestCase with one Request for each method
option and click on OK.
(5)
After click on OK, will display
a new dialog box as below:-
Note:- Now
after importing the WADL file the project will appear as below:-
Note:
- As we have 4 types of services according to WADL file, So here we can see the
4 test steps created bydefault inside the TestSuite. The available services as
per WADL are
sayPlainTextHello, sayXMLHello, sayHtmlHello and sayJSONHello.
(6)
Right click on the project Sample_Rest_Mocking
and select New MockService option.
(7)
After click on New
MockService option, provide any name in the below text box:
(8)
Right Click on SampleMockService
and select the option Show MockService Editor. Screen will appear as
below:-
(9) Click on Sets Options for this MockService, In the below fig. we can see the option.
(10) After click on Sets Options for this MockService, the window
will appear as below:-
Here the Path “/”
is responsible to handle all the request URL, If we will configure the path
like above then it will serve all request services coming from different-different
URL's in soapUI, but if we need to deploy this soapUI project as a war file in
any servlet container then it will not work, The reason behind this is while
making war of this soapUI project, a component is generated which is
com.eviware.soapui.mockaswar.MockAsWarServlet,
and This class is acting like dispatcher servlet, In this class, Inside
dispatchRequest method, a condition is defined which is given below:-
pathInfo.equals(
mockRunner.getMockService().getPath() )
Here pathInfo is the request
path(URL) and mockRunner.getMockService().getPath() is the value of Path
attribute which we mentioned above during MockService configuration. If both path's are equal then only
OnRequest Script will get triggered otherwise OnRequest script will not get triggered (as we
are writing the Mock Response representation codes in OnRequest Script in
MockService Editor). So if OnRequest
script will not get triggered we are not
able to get responses after sending available requests.
So if we have to deploy this MockService in
any ServletContainer then we need to create a war for this soapUI project at that time it
is good to define separate MockServices for handling each request URL. Otherwise the
value for path attribute is Ok as “/”, if we want to execute only in soapUI(If we don't
want to deploy in any servers).
(11)
Configure the MockService
attribute values as below:-
Here Docroot is the path where I kept my response files.
C:\sample-Rest-Mocking/docroot/
- Path where I placed my response files.
(12) Place the
required code in MockService – OnRequestScript. Below is the source
code which I placed in MockService OnRequestScript(Screenshot is attached
below).
Source Code:-
def queryString =
mockRequest.getHttpRequest().getQueryString()
def httpResponse = mockRequest.httpResponse
def mediaType =
mockRequest.getHttpRequest().getHeader("Accept")
def groovyUtils = new
com.eviware.soapui.support.GroovyUtils(context)
//This variable is used to get the soapui
project path
def path =
groovyUtils.projectPath + "/docroot/"
log.info "projectPath-->"+path
if
(mockRequest.getMethod() == "GET" &&
mediaType=="application/json"){
mockRunner.returnFile(httpResponse,new
File(path + "JSONResponse.js"))
log.info "Response returning for
Content-Type application/json"
return new
com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest)
}
if (mockRequest.getMethod() ==
"GET" && mediaType=="text/plain"){
mockRunner.returnFile(httpResponse,new
File(path + "test.txt"))
log.info "Response returning for
Content-Type text/plain"
return new
com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest)
}
if (mockRequest.getMethod() == "GET"
&& mediaType=="text/xml"){
mockRunner.returnFile(httpResponse,new
File(path + "User.xml"))
log.info "Response returning for
Content-Type text/xml"
return new com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest)
}
if (mockRequest.getMethod() ==
"GET" && mediaType=="text/html"){
mockRunner.returnFile(httpResponse,new
File(path + "htmlSuccess.html"))
log.info "Response returning for
Content-Type text/html"
return new
com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest)
}
(13)
Now Click on the
Option Starts this MockService on the specified port and
endpoint (Green button) in SampleMockService.
(14) Double click on HelloExample
Rest Request:-
running as we have seen
in above steps. After sending the request the output will appear as
below:-
Mock
Response of HelloExample
Request where Content-Type is text/plain:-
Plain
Text Mock Response :-
<data contentType="text/plain"
contentLength="73">
<![CDATA[Hello by text document, It's a sample example
using soapUI Rest Mocking]]>
</data>
Note :-
Make a txt file with any content and name it as
test.txt and place inside docroot directory where you saved this
current soapUI project in FileSystem. For example : - this soapUI project saved
location is C:\sample-Rest-Mocking and
soapUI mock response path is like C:\sample-Rest-Mocking\docroot.
(15)
Now send other requests like HelloExample
1, HelloExample 2, HelloExample 3 sequencially.
The Mock Response is as below:-
Mock Response
of HelloExample 1 Request where Content-Type is text/xml :-
XML
Mock Response :-
<xml>
<user>
<username>Gaurav</username>
<password>123@**</password>
</user>
</xml>
Note :-
Save this content as User.xml and place inside docroot directory where
you saved this current soapUI project in FileSystem. For example : - this
soapUI project saved location is C:\sample-Rest-Mocking and soapUI mock response path is like
C:\sample-Rest-Mocking\docroot.
Mock Response of HelloExample 2
Request where Content-Type is text/html :-
HTML
Mock Response :-
<html>
<head/>
<title>MySuccessPage</title>
<body>Hello Rest
Service</body>
</html>
Note :-
Save this content as htmlSuccess.html and place inside docroot directory
where you saved this current soapUI project in FileSystem. For example : - this
soapUI project saved location is C:\sample-Rest-Mocking and soapUI mock response path is like
C:\sample-Rest-Mocking\docroot.
Mock Response of HelloExample 3
Request where Content-Type is application/json :-
JSON
Mock Response :-
{"state": {
"name":
"India",
"state":
"Andhra Pradesh",
"pincode":
500048,
"capital":
"Delhi",
"majorCities": [
"Mumbai",
"Kolkata",
"Chennai",
"Bangalore",
"Hyderabad"
]
}}
Note :-
Save this content as JSONResponse.js and place inside docroot directory
where you saved this current soapUI project in FileSystem. For example : - this
soapUI project saved location is C:\sample-Rest-Mocking and soapUI mock response path is like
C:\sample-Rest-Mocking\docroot.
Finished
Note - In the continuation with REST web-service mocking, very soon i will post tutorial for how to generate dynamic mock responses using soapUI.
Hi Gaurav,
ReplyDeleteWhen can i expect the post REST web-service dynamic mock responses using soapUI ?
Thanks,
Praveen
Hi Praveen,
DeleteI will try to publish the post as the earliest. so don't worry
Thanks
Gaurav
Hi Again,
ReplyDeleteIf i want to mock rest service having three methods, do i need to create three mockservices ?
Thanks,
Praveen
Hi Praveen,
ReplyDeleteAs you can see in the above post, I have four methods in the rest service and I am using only one mockservice to provide the mockResponse. But if you have two different service and each is having 3-4 methods, then for each service it is better to create one mockservive. Suppose I have a service security and inside security i have other service like login, transaction. Again inside login, I have session in and session out methods and in Transaction i have transaction by ID and transaction by name, then it is good to create two mockservice, one for login and one for transaction. Go to Step no-10 and understand this.
Hi Gaurav,
ReplyDeleteIn the above post you have written script to send the response for single resource, i mean you are differentiating with the type of request. But in my case i have two rest resources like below
1)http://localhost:port/api/rest/gamedetails?gameid=12
2)http://localhost:port/api/rest/game/12
first one is to get the details and second is to complete the game.
I don't have WADL, so how should i process two request in one mock service.
Thanks,
Praveen
Hi Praveen,
ReplyDeleteAccording to STEP-10, if you will configure mockservice path="/" then it will handle your all rest resources,So with only one mockservice you can complete your work and it will work in your soapUI perfectly. But if you will make a war package of this and deploy in any servlet container then that time it will not trigger your mockservice.
So if you just want to mock using soapUI without deployment then you can go with one mockservice. But if you want deployment then you have to create two mockservice, one for each resource.
Thanks
Gaurav
Hi Kumar,
ReplyDeleteI have followed the steps what u have given in "
REST web-service With CRUD Operations Using Spring and Hibernate" but I am getting this error "org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.IllegalAccessError: tried to access method net.sf.ehcache.CacheManager.()V from class org.hibernate.cache.EhCacheProvider"
please help me here, how to solve this.
Thanks,
sayed
Could you please provide me the complete Log Stack trace and when You are getting this exception?
DeleteI am trying to mock the HTTP POST operation without using any groovy script. Is there any easy way to do it using soap ui?
ReplyDeletesir i like your movies...
ReplyDelete