Tuesday, 7 May 2013

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

Creating Dynamic MockServices for soap based web-service

In the earlier post, I explained that how to create web-services using JAX-WS (Java API)?  Now I am going to explain how to mock the services and produce dynamic responses using soapUI Web Service Testing Tool?

In the above link, I have published the WSDL file, now we will use the same WSDL file for creating the dynamic Mock services.

Ques:- What is mocking?

Answer: - In oops programming concept, mock objects are simulated objects that emulate (duplicates) the behavior of real objects in disciplined way. Mock object are created to test the behavior of some other object
The purpose of mocking is to allow us to test our application components in isolation. The purpose of all mocking frameworks is to allow us to set up expectations and assert that those expectations were met in our tests.

Ques:- In which situations we can use mock services?

Answer: - Below are the following reasons where it may be useful to use a mock object in its place:
  • Due to unavailability of live services because of network failure or unauthorized access.
  • In order to avoid database connections, which is reducing the application performance.
  • Still the new services are not available to test or under development.
Finally, we can say that Mocking is an excellent tool to test a specific object under well disciplined conditions.

Steps:- 

This is the example of soap 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 WSDL file, where we published our services during the creation of web-service using JAX-WS.
The WSDL file published path is - http://localhost:7070/jaxws/genericMethods?wsdl



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


  • Above screen will appear, then again click on OK, After Click on OK below dialog box appears. Now again click on OK.


  • After Click on OK, now the screen will be as follows, so again click on OK button.

  • Now the below screen is prompting for the mockservice name to create, so I had given the mock service name is as GenericMethodsImplPortBinding-MockService. After click on OK will generate the Test Suite as well as Mockservices.
 

  • Now the project structure will look as follows:-



  • Now click on the option Sets options for this MockService in Show MockService Editor option. This (Show MockService Editor) option is available on right click of mock service.



  • Now, we should configure the MockService options like below and again click on OK button. Just change the hostname.



Now inside Mock Service we have below three Mock operations:-
  • getFactorial
  • getOddAndEven
  • getPrimeNumber
On double click of getFactorial will open the below screen, Select the Dispatch option as SCRIPT. By default it is SEQUENCE. Now I am going to place the Groovy script for getting the factorial of the given number(Number is coming through the mock request). The Groovy script source code is available below:-
 


 Groovy Script Source Code for Getting the factorial number.

           
           import groovy.util.XmlSlurper
           int fact = 1;
           def parsedContent = new XmlSlurper().parseText(mockRequest.requestContent)
           def number = parsedContent.Body.getFactorial.toString()
           log.info "number is->"+number
           /* This method is used for identifying the number format exception */
                public boolean isParsableToInteger(String strValue) {
                try {
            strValue.toInteger();
            return true;
        } catch (NumberFormatException nfe) {
            /* This fact value will be available if we will provide String instead of number */
            requestContext.fact = "Not a valid number";
            return false;
        }
                }
                if(isParsableToInteger(number)){
                                                number = number.toInteger();
                                if (number < 0 ){
           /* This fact value will be available if we will provide -ve number instead of +ve number */
            requestContext.fact = "Number should not be -negative";
          }
          else
           {
              for (int i= 1; i<=number; i++){
                                    fact = fact * i;
           }

         /* This fact value will be available if we will provide +ve number */
         requestContext.fact = fact;
       }
}   

In the above Groovy script I have added some positive and negative scenarios, like
  • If the number is Negative Number (Negative scenario).

  • If the String is passed instead of number (Negative scenario).

  • If the number is Natural number (Positive scenario).

Now double click on the response 1 of getFactorial mock operation and place the value of return data as below: - Note: - (<return>${fact} </return>), For getting the large number of factorial we have to declare number as Long Type.


Setting the return value in getOddAndEven Response 1 :- 




Similarly as above we will place the groovy script for getOddAndEven and getPrimeNumber Mock Operations and will set the response return value for both the mock operations.

  •  Placing the Groovy script source code for getOddAndEven mock operation:-
 

Groovy Script Source Code for Getting the OddAndEven number.

          
           import groovy.util.XmlSlurper
           int OddAndEven = 1;
          def returnValue;
          def parsedContent = new XmlSlurper().parseText(mockRequest.requestContent)
           def number = parsedContent.Body.getOddAndEven.toString()
           log.info "number is->"+number
          /* This method is used for identifying the number format exception */
                public boolean isParsableToInteger(String strValue) {
                try {
            strValue.toInteger();
            return true;
           
        } catch (NumberFormatException nfe) {
            /* This fact value will be available if we will provide String instead of number */
            requestContext.OddAndEven = "Not a Valid Number";
            return false;
        }
                }
        if (isParsableToInteger(number)) {
            number = number.toInteger();
           if (number < 0 ){
            log.info "Number should be non-negative.";
            /* This fact value will be available if we will provide -ve number instead of +ve number */
            requestContext.OddAndEven = "Number should not be -negative";
          }
          else{
                 if (number % 2 == 0)
                returnValue = number + " is even number";
            else
                returnValue = number + " is odd number";
                requestContext.OddAndEven = returnValue;
                }
        }

Setting the return value in getOddAndEven Response 1:- (Note: - <return>${OddAndEven}</return>)





Placing the Groovy Script source code for getPrimeNumber mock operation:-

 



Groovy Script Source Code for Getting the Prime number.

          import groovy.util.XmlSlurper

          int primeNumber = 1;

         def returnValue;

         def parsedContent = new XmlSlurper().parseText(mockRequest.requestContent)

        def number = parsedContent.Body.getPrimeNumber.toString()

        log.info "number is->"+number

         /* This method is used for identifying the number format exception */

                public boolean isParsableToInteger(String strValue) {
                try {
            strValue.toInteger();
            return true;
        } catch (NumberFormatException nfe) {
            /* This fact value will be available if we will provide String instead of number */
            requestContext.primeNumber = "Not a Valid Number";
            return false;
        }
                }
        boolean flag = true;               
        if (isParsableToInteger(number)) {
            number = number.toInteger();
         if (number < 0 ){
         log.info "Number should be non-negative.";
            /* This fact value will be available if we will provide -ve number instead of +ve number */
            requestContext.primeNumber = "Number should not be -negative";
          }
          else{
                int result;
          for (int i = 2; i <= number / 2; i++) {
                result = number % i;
                if (result == 0) {
                    flag = false;
                    break;
                }
            }
            if (flag){
                returnValue = number + " is Prime Number";
                requestContext.primeNumber = returnValue;
            }
            else{
                returnValue = number + " is not Prime Number";
                requestContext.primeNumber = returnValue;
            }
        }
                }
 

Setting the return value in getPrimeNumber Response 1:- (Note: -<return>${primeNumber}</return>)



Now the setup is completed and we are ready to start testing. Start the mock service by double click on GenericMethodsImplPortBinding-MockServiceand click on the option starts this Mock Service on the specified port and endpoint (Note:- we have to click on the Green arrow button for starting the mockservice otherwise by right clicking on mock service and choosing Start Minimized will also start the service). Now mock service is running on the 8088 port number, that we can check in the below image:-






Now, double click on the getFactorial Test Request inside GenericMethodsImplPortBinding TestSuite, it will open the below screen, edit the URl as http://localhost:8088/mockGenericMethodsImplPortBinding.


Test for getFactorial by passing a valid number then click on the submit request to specified endpoint url option,
Scenario - 1,



Scenario - 2,
After passing a Negative number then observe the response:-


Scenario - 3,


After passing a string instead of number then observe the response-





Test for getOddAndEven mock operation, change the endpoint URL similar to getFactorial method

Scenario - 1,
pass a valid number (Test for Even number).


Scenario - 2,


After passing odd number then observe the response-



Scenario - 3,


After passing a negative number then observe the response-



Scenario - 4,

After passing a string instead of number then observe the response-


Test for getPrimeNumber mock operation, change the endpoint URL similar to getFactorial method and follow the same steps as above.

This is the way through which we can generate dynamic mock responses for soap based web-services using soapUI.

No comments:

Post a Comment