Mockservice Script Overview

Source: Internet
Author: User
Tags stop script soapui

while the static mockoperation and Mockresponse models can give you a certain amount of flexibility, adding more dynamic behaviors to your service makes it useful to simulate complex service functions. For example, you might want to:

    • Modify their values from the request to the response transfer value
    • Look at some data request and select the response to return based on its value
    • Read response from Database
    • Create a custom HTTP response manually
    • Wait a minute...

Let's take a look at how to implement these in a particular, but we will first give you an overview of how you make your mockservices more dynamic.

1. Mockservice Script Overview

There are many script events available for the Mockservice itself:

    • start and stop scripts; These are all shared objects (such as collections or database connections) that are turned on or off.
    • onrequest script; This is the main handler for simulating non-soap behavior (rest, etc.); SOAPUI does any internal dispatch, there is no response back to the client (thereby bypassing the entire SOAPUI scheduling mechanism) before it is called
    • Afterrequest script: Primarily used for custom logging and reporting functions

All these are available from the Mockservice window:

for mockoperations a script may be available; Selecting the Script option allows you to use a script that determines the return to the client to Mockresponse, such as an example

Finally, for mockresponse you can specify a "response script":

The ability to create and return a mockresponse message to the client before a particular script will be executed; This is the main place where the content of the dynamic response is generated.

In Soapui, you can also define event handlers at the project level to specify that all mockservices are used to run the project;

The available impersonation-related handlers are:

    • Mockrunlistener.onmockresult-Corresponds to Mockservice afterrequest script
    • Mockrunlistener.onmockrunerstart-Corresponds to Mockservice startup script
    • Mockrunlistener.onmockrunerstop-corresponds to Mockservice stop script
    • Mockrunlistener.onmockrequest-Corresponds to Mockservice onrequest script
2. Simulation Handler Object

Many objects are usually available in most scripts :

    • context-objects used to store Mockservice scopes, such as database connections, security tokens, etc.
    • RequestContext -Used to store impersonation request scope objects, such as dynamic content that will be inserted into the response message
    • mockrequest -The object that corresponds to the actual request made by the Mockservice. through this object, you can relate to incoming messages, header information, and so on.
    • Mockresult -encapsulates an object that allocates the result of the request, which is available in the Mockservice.afterrequest script.
    • Mockresponse  /  mockoperation -access to the underlying configuration and functionality of the object
    • Mockrunner -The object that corresponds to the execution of the Mockservice; This gives you access to previous simulation results, etc.

Well, now let's go deep and see what these can be used for!

3. Transfer values from request to response

This is a simple script in mockresponse; the script uses the properties of the Mockrequest object to get the incoming request, by extracting the desired value of the XPath, and then creating the result to write to the RequestContext property:


// create XmlHolder for request content
2. def  holder =  new  com.eviware.soapui.support.XmlHolder( mockRequest.requestContent ) 3.  4. // get arguments and sum 5. def  arg1 = Integer.parseInt( holder[ "//arg1" ] ) 6. def  arg2 = Integer.parseInt( holder[ "//arg2" ] ) 7.  8. requestContext.sum =  arg1 + arg2

as you can see, the extracted values are assigned to RequestContext (which is specific to this requirement) with a "sum" attribute. :

Panel left display sent to us?? Mockoperation last request.

4. Create a response from a testcase result

This is a more complex one; we will create a soapui testcase that executes first, and use its results to populate the Mockresponse message mockresponse script:

//create xmlholder for request contentdef holder =NewCom.eviware.soapui.support.XmlHolder (mockrequest.requestcontent)//Get target TestCasedef project =mockResponse.mockOperation.mockService.projectdef testCase= project.testsuites["TestSuite 1"].testcases["TestCase 1"]//set arguments as PropertiesTestcase.setpropertyvalue ("Arg1", holder["//arg1"]) Testcase.setpropertyvalue ("Arg2", holder["//arg2"] )//Run TestCasedef runner = Testcase.run (NewCom.eviware.soapui.support.types.StringToObjectMap (),false )if(runner.status.toString () = = "Finished") Requestcontext.sum= Testcase.getpropertyvalue ("Sum" )ElseRequestcontext.sum= "Error:" + Runner.reason

the script first gets to keep the testcase target running, sets some properties of the parameter value, and then executes it. If all goes well, the result is read from another TestCase property and returned by the same mechanism, otherwise an error message is displayed.

If we just wanted to execute a single request and return a request for a response (Soapui's turn becomes a "proxy"), we can;

//Get target Requestdef project =MockResponse.mockOperation.mockService.projectdef Request= project.interfaces["newwebserviceportbinding"].operations["sum"].getrequestbyname ("Request 2"))//set request from incomingRequest.requestcontent =mockrequest.requestcontent//Submit Request AsynchronouslyRequest.submit (NewCom.eviware.soapui.impl.wsdl.WsdlSubmitContext (Request),false )//save Response to contextRequestcontext.responsemessage = Request.responsecontentasxml

here, we assign the entire response to the RequestContext attribute; The actual mockresponse message is just an extension of a property;

5. Select the request-based response

The script specifies the mockoperation level and uses the same code as above to extract the input values from the incoming request. based on some validation it returns the name of the Mockresponse returned to the client. the script is as follows:

//create xmlholder for request contentdef holder =NewCom.eviware.soapui.support.XmlHolder (mockrequest.requestcontent)//Get Argumentsdef arg1 = holder["//arg1"]def arg2= holder["//arg2"]if(!com.eviware.soapui.support.stringutils.hascontent (arg1) | | !com.eviware.soapui.support.StringUtils.hasContent (arg2))return"Invalid Input Response"Try{integer.parseint (arg1) Integer.parseint (arg2)}Catch(e) {return"Invalid Input Response"}//Select valid response randomlydef r =math.random ()if(R < 0.33 )   return"Simple Response"Else if(R < 0.66 )   return"Call TestCase"Else    return"Call Request"

Contains mockresponses:

The requestcontext variable used in the script is, of course, the same as we saw in the previous example, allowing you to pass values from the dispatch script to Mockresponse. For example, we can add a requestcontext for the "Freememory" property:

//Add diagnostics requestcontext.freememory = Runtime.runtime.freeMemory () ...

This will make it available for all mockresponses attribute extensions defined in mockoperation;

This will return

to the client.

6. Responses read from the database

This involves doing more work, because we need to create and close database connections that we can use in our scripts. It is best to start the script in Mockservice as follows;

Import GROOVY.SQL.SQL // Open Connectiondef mockservice == sql.newinstance ("jdbc:mysql://" + mockservice.getpropertyvalue (" Dbhost ") +         " DbName "                      ),                     " Dbusername ")," Dbpassword ")," Com.mysql.jdbc.Driver "" succesfully connected to Database "//  Save to context context.dbconnection = sql

Here we establish a connection (using the built-in database support Groovys ') to the configured database (the parameter configuration is taken from the mockservice nature), and then keep the text in place so that all of its scripts are available. mockservice Stop, the corresponding script closes the connection of course is needed;

// Check for connection in context if NULL ) {    "Closing database Connection"    context.dbConnection.close ()}

}

So if we start and stop Mockservice we will see the following in the log:

> perfect! In this concrete and simple example I have a table containing the entire SOAP response returned to the client ,   . I choose to do all the logic in a single mockresponse script:

//create xmlholder for request contentdef holder =NewCom.eviware.soapui.support.XmlHolder (mockrequest.requestcontent)//get arguments and Sumdef arg1 = Integer.parseint (holder["//arg1"]) def arg2= Integer.parseint (holder["//arg2"] )//get connection and perform querydef sql =context.dbconnectiondef Row= Sql.firstrow ("select * from tb_saved_messages where arg1 =?") and arg2 =? ", [Arg1, arg2])//Save result to property for responseRequestcontext.responsemessage = Row.responsemessage

Very straightforward:

    • Extract the desired value from the request
    • Gets the database connection from the context
    • Execute Query
    • RequestContext property of Write response

The response message itself only has the content of the property extension:

This causes the entire message to be written to the response.

7. Create a custom response

This is the only way SOAPUI is currently simulating a rest or more complex HTTP service; the Mockservice level onrequest script allows you to directly access the underlying HttpRequest and HttpResponse objects allowing you to create any responses you like. All you need to determine whether the script returns an object mock result tells Soapui to stop processing the request. So, for example, if we were to deal with it, we could make the following put request:

//Check for PUTif(MockRequest.httpRequest.method = = "PUT") {def result=NewCom.eviware.soapui.impl.wsdl.mock.WsdlMockResult (mockrequest)//Build Pathdef path = mockRunner.mockService.docroot + File.separatorchar +mockRequest.httpRequest.queryString Path= Path.replace ((Char)‘/‘, File.separatorchar)//Create File object and check if it doesnt already existsdef file =NewFile (path)if( !file.exists ()) {      //Create Directories      if(Path.lastindexof ("+file.separatorchar) > 1 )         NewFile (path.substring (0, Path.lastindexof ("" +File.separatorchar)). Mkdirs ()//Write ContentFile <<MockRequest.httpRequest.inputStream MockRequest.httpResponse.status= 201Log.info"File written to [$file. Absolutepath]"   }   Else{mockRequest.httpResponse.status= 403     }      returnresult}

As you can see, the request principal specifies the path by using the URL of the document root set in the Mockservice Options dialog box;

The necessary directories are created and the corresponding status codes are returned. For example http://localhost:8299/?/some/path/file.dat&NBSP; with the HTTP put and message body will cause the file to be created. You can do this using an HTTP Testrequest step for soapui:

and now, because the file was created in the Mockservices "document root directory, you can use your Web browser and specify http://localhost:8299/?/some/path/file.dat will get the appropriate file.

8. Last Words

That 's it! the possibility of scripting Mockservices makes it easy to create dynamic and "lifelike" mockservices, a document that should give you a better understanding. Good luck!

Mockservice Script Overview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.