Beginning soapUI Scripting 5: Groovy Assertions

So far we've looked at a few scripting "containers" in soapUI-- components where you can easily insert Groovy script to extend or customize functionality-- including Groovy Script test steps and set up and tear down scripts at the test case and test suite levels.  In this post we'll look at Groovy Script assertions, which are useful in situations where soapUI's built-in assertions don't quite fit the bill.

Script assertions can be added to a test request through the standard Add Assertion dialog, launched from the test request editor window:



Test Request Editor (Add Assertion button outlined in red)

Once you select Script Assertion (listed in its own Script category) as the type of assertion you want to add, click the Add button and provide a name for your new assertion to bring up an empty Script Assertion window:



Script Assertion Editor

As with other scripting components, script assertions come with several built-in variables.  We've already seen the log and context variables with Groovy Script steps and set up and tear down scripts, but script assertions also come with the messageExchange variable, which provides quick access to request and response data.

Here's a quick example of some script assertion code based on the periodic table service I've used in other posts (you can download the very, very small project here to play around with the script assertion yourself). It essentially replicates the functionality of a standard Contains assertion, looking for the appropriate string in a response from the service's GetAtomicNumber operation for the element hydrogen:

responseData = messageExchange.getResponseContent() log.info(responseData) assert responseData.contains("<atomicnumber>1</atomicnumber>")
The first line grabs the content of the test request's response (as a string) and assigns it to the variable responseData; it also illustrates the convenience of the built-in messageExchange variable: we're able to access test request data with a single method call (I'll look at some of its other methods in a separate post in the near future). The second line is strictly for informational purposes; it just writes the responseData string to the script log.  The assert keyword is introduced in the second line.  It asserts that the expression following the keyword is true (in this case, we're asserting that the responseData string contains the correct atomic number for hydrogen. If the asserted expression is false, the assert statement (and consequently, the entire script assertion) fails.

The assertion as written should pass, but try changing the substring in the contains method to something else-- changing the atomic number to 2, for example.  You'll see that the assertion is flagged as a failure in the UI just as a standard assertion failure would be flagged:



Script Assertion Failure