Saturday 11 May 2013

How to create dynamic MockServices using soapUI for REST web-services?


Creating Dynamic MockServices for REST web-service

In the below post, I mentioned that how to publish a web-service having parametrized methods, and I provided the information to get the WADL file while application is running in any servlet container.

Below is the link available through which we can generate the WADL file for the parametrized methods and the same WADL file I am using in order to create REST mocking using soapUI.


Now with this post I will provide the information to Mock those published REST web-services using soapUI Web Service Testing Tool and presenting dynamic mock responses for the each web-service requests.

Steps:- 

This is the example of REST web-service mocking and generating dynamic mock responses.

  • Open soapUI, I am using 4.5.1 version of soapUI
  • Go to File menu and select New soapUI project and give the path of the WADL file, where we published our services during the creation of RestWebServiceWithParametrizedMethods web-service using JERSEY.
  

  • As per the above screenshot, select the checkbox for Creates a Test Suite for the imported WSDL or WADL and Click on OK.


  • Above screen will appear, then select radio button for option Single TestCase with one Request for each method then click on OK, After Click on OK below dialog box appears. Now again click on OK.
 
 
  • After Click on OK, now the project structure will be as follows:-


  • Now right click on RESTWithParametrizedMethodsMocking project and select New MockService, after click on the New MockService, below dialog box will appear, then place an appropriate name and click on OK.



  • Double click or pressing enter on the Mock Service will display MockService editor, now in the MockService editor click on the option Sets options for the MockService. Configure the MockServer with the appropriate options as below and click on OK.


Inside RESTWithParametrizedMethodsMocking TestSuite, we have three Test Steps:-
  • factorial
  • countVowels
  • name
So, in the MockService onRequestScript option, we have to provide the specific Groovy code for the generation of exact dynamic values just like live services and the generated dynamic mock responses depends on the data provided in the Request parameter.

Groovy Script Source Code for Getting the factorial number, counting vowels and displaying the passed names in request parameter. In the below groovy script code I am also checking the below conditions :-
  • The passed parameter is number or String
  • The passed parameter is positive or Negative.
Place this Groovy script code in MockService OnRequest Script.


            
def httpResponse = mockRequest.httpResponse          
                         
                         int fact = 1;

                         def result = "Not a valid Number";
                         
                         def strWordForVowelCount;

                         def number;
          
           def uriPath = mockRequest.getPath()

            /* This method is used for identifying the number format exception */
            public boolean isParsableToInteger(String strValue) {
            try {
            strValue.toInteger();
          
            return true;
           
        } catch (NumberFormatException nfe) {
         
          return false;
        }
            }
                       
            /* This method is used for counting the vowels from the given string */        
            public String countVowels(String word){
                       
               int count =0;
       
        for(int i = 0; i < word.length(); i++)
        {
            if(word.charAt(i) == 'a' || word.charAt(i) == 'A')
            {
                count++;
            }
            else if(word.charAt(i) == 'e' || word.charAt(i) == 'E')
            {
                count++;
            }
            else if(word.charAt(i) == 'i' || word.charAt(i) == 'I')
            {
                count++;
            }
            else if(word.charAt(i) == 'o' || word.charAt(i) == 'O')
            {
                count++;
            }
            else if(word.charAt(i) == 'u' || word.charAt(i) == 'U')
            {
                count++;
            }
        }
       
        log.info "Number of vowels in the given string is : " + count;
              
               return String.valueOf(count);
            }
          
           
     /* This Block will get executed when requested for countVowels method */           
            if(mockRequest.getMethod() == "POST" && uriPath == "/FactorialUsingRestWebService/rest/basic/countVowels"){

                        mockRequest.httpResponse.status = 200

                        httpResponse.addHeader("Content-Type","text/plain");                      

                        def paramDetails = mockRequest.getRequestContent()

                        strWordForVowelCount = paramDetails.toString();
                 
                 result = countVowels(strWordForVowelCount)+" vowels found in the given string "+strWordForVowelCount;
                       
                        mockRequest.httpResponse.writer.print(result);
                       
                        return new com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest)
      
    }

            /* This Block will get executed when requested for getFactorial method */
            if(mockRequest.getMethod() == "POST" && uriPath == "/FactorialUsingRestWebService/rest/basic/factorial"){

                        mockRequest.httpResponse.status = 200

                        httpResponse.addHeader("Content-Type","text/plain");                      

                        def paramDetails = mockRequest.getRequestContent()

                        number = paramDetails.toString();
                 
                 if(isParsableToInteger(number)){
                                   
                                    number = number.toInteger();
                                   
                        if (number < 0 ){
          
             result = "Number should not be negative";
          }
          else
           {
              for (int i= 1; i<=number; i++){
                            
                            fact = fact * i;
           }
                       
                        result = "The Factorial of the number "+number+" is : "+fact.toString();

          log.info "Factorial of the given number is : " + result;
            }
       }    
                        mockRequest.httpResponse.writer.print(result);
                       
                        return new com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest)
     }
   
      
    /* This Block will get executed when requested for displayName method */         
    if(mockRequest.getMethod() == "POST" && uriPath == "/FactorialUsingRestWebService/rest/basic/name"){

                        mockRequest.httpResponse.status = 200

                        httpResponse.addHeader("Content-Type","text/plain");

                        def paramDetails = mockRequest.getRequestContent()

                        result = "My Name is "+paramDetails.toString();

                        mockRequest.httpResponse.writer.print(result);
                       
                        return new com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest)
      
    }
  After Placing the Groovy Script code in OnRequest Script of RESTParametrizedMethodMockService.


Now click on the option start on the MockService on the specified port and endpoint.


For Test Step -1 i.e. factorial

Now double click on the factorial Test Step and select Accept = text/plain, and pass any integer to get the result, here I passed 5 and the result is available below:-

Scenario – 1, when Request Parameter is passed as 5.
 
Scenario – 2, when Request Parameter is passed as -9.



Scenario – 3, when Request Parameter is passed as String.
 
 
Scenario – 4, when Request Parameter is passed as 8.


For Test Step -2 i.e. countVowels

Now double click on the countVowels Test Step and select Accept = text/plain, and pass any String to get the counted vowels as result, here I passed KUMAR GAURAV and the result is available below:-

Scenario – 1, when Request Parameter is passed as KUMAR GAURAV.
 

Scenario – 2, when Request Parameter is passed as KUMAR AADITYA.
 
 
Scenario – 3, when no Request Parameter is passed.


For Test Step -3 i.e. name(displaying names)

Now double click on the name Test Step and select Accept = text/plain, and pass any String to get the result, here I passed KUMAR GAURAV and the result is available below:-

Scenario – 1, when Request Parameter is passed as KUMAR GAURAV.



 Scenario – 2, when Request Parameter is passed as Elizabeth.


This is the way to create REST MockService for providing the Dynamic MockResponses using soapUI tool. If required we can generate Random number or Alphanumeric random number(Use RandomStringUtils) for providing dynamic response Id's for each web-service request.

No comments:

Post a Comment