How to Handle Exception in SoapUI Groovy Scripts – SoapUI Tutorial #11

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 1, 2024

In this SoapUI tutorial, we will look at how to handle exception in SoapUI Groovy scripts. Let’s get started. 

Handling runtime exceptions in groovy is similar to Java as the Java libraries are integrated. However, we will discuss the basic concepts in SoapUI and go into the details of exception handling in Java.

This is tutorial #11 in SoapUI tutorials series. It is the last tutorial for the free version of SoapUI. There are a couple more topics remaining in this series which are on SoapUI pro features, REST and SOAP services, and data driven testing in SoapUI. Let’s begin the tutorial with a brief introduction about an exception.

How To Handle Exception in SoapUI Groovy Scripts

Exception handling in Groovy script

What is an exception

An exception is an error that is encountered during the execution of a program. This can happen due to a number of reasons such as invalid data, network connection loss, trying to open files that are unavailable, accessing invalid class, memory leakage, i.e. forcing the system to work with huge amounts of data, database servers being unresponsive, etc. These errors may be due to users, developers or hardware resources.

Internally, when an exception is encountered during the execution, SoapUI will try to find the handler. Handler is a block that contains the code to catch the exception.

Exceptions are categorized into the following two types:

  1. Runtime exception
  2. Compile time exception – not applicable to SoapUI as it does not have an explicit compiler

Look at the following screenshot which shows us the runtime exception for the invalid code. In the below script we tried to divide an integer by 0. In the error dialogue it can be seen that the exception is raised from java libraries and the error message is Division by zero.

Exception Handling in Groovy Scripts 1

We can catch this exception during the execution and handle it programmatically. Before that, we will see some of the important keywords that are used in the java exception concepts. Some of the keywords can also be used in the groovy script. They are as follows:

  • Throw – This keyword help us to throw an exception manually i.e. to throw user defined exceptions
  • Throws – It is used to call the pre-defined exceptions from the method definition. This will catch the exception if there is any runtime error found during the execution.
  • Try and Catch – “try” keyword is used with “catch” keyword. If we can predict the portion of the program where the exception can arise during the execution, we can use “try” block in that place. At the end of the “try” block, “catch” block should start to catch an exception. Inside the catch block, we have to write to the handler to handle the exception.
  • Finally – This is the default and optional block in the exception structure. If we need any statements to be executed at the end of the program, like cleaning unused objects, closing connections etc. that can be done inside this block.

The following is the general structure of an exception

try
{
<code to be executed>
}
catch <exception name>
{
<exception handler>
}
finally
{
<default statements>
}

Now let us implement the exception handler in the sample code which we have already seen in the screenshot.

Add a new test suite under the GlobalWeather project. Then add a test case and groovy script test step under the test step. In the script editor, enter the following script.

// initializing the variables
int a = 10;
int b = 0;

// try, catch block
try
{
&nbsp;&nbsp; &nbsp;// Dividing a number by zero
&nbsp;&nbsp; &nbsp;int c = a/b;
&nbsp;&nbsp; &nbsp;log.info('Result :' + c);
}
catch(Exception expObj)
{
&nbsp;&nbsp; &nbsp;// Exception Handler
&nbsp;&nbsp; &nbsp;log.info('You are trying to divide ' + a + ' by ' + b + '. This is not possible actually!');
}

The above script produces the following results as shown in the screenshot.

Exception Handling in Groovy Scripts 2

As we discussed earlier, we tried to divide “A” “B” which is zero. So the “catch” block gets executed and shows the user-defined message in the log. Notice that in the “catch” statement, we have used Exception class which is the superclass in Java for all the built-in exceptions. All pre-defined exception classes are inherited from the Exception class. To handle unpredictable runtime exceptions, we can use the Exception class in the “catch” block.

Let us now modify the above script to get the required results. Look at the following screenshot:

Exception Handling in Groovy Scripts 3

Let us now try this on our regular web service testing. In the following script, we did not use the try-catch block so we will get the runtime exception.

// Initializing array with 5 elements
String[] countryNames = new String[5];

// Assigning values to the array
countryNames[0] = 'India';
countryNames[1] = 'Cyprus';
countryNames[2] = 'Canada';
countryNames[3] = 'Austria';
countryNames[4] = 'Mauritius';

// Iterate the array elements and assign value to the global property
for(int idx=0; idx&amp;lt;=5; idx++)
{
&nbsp;com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( &amp;quot;CountryName&amp;quot;, countryNames[idx]);

def testStep = testRunner.testCase.testSteps['GetCitiesByCountry'];
testStep.run(testRunner,context);

log.info('Executed at ' + idx + ' times!');
}

The above script will throw an exception called ArrayIndexOutOfBoundsException because the script is trying to access invalid array index i.e. 5 which is not available.

(Click on the image for an enlarged view)

Exception Handling in Groovy Scripts 4

As you can see in the above script, we have initialized “countryNames” array with the size of five. It accepts only five string values i.e. country names. Inside the iterative statements, we have checked as idx < = 5. So the loop will be iterating up to 6 times and it will try to search 6th element in the array. Since the value will not be there it throws a runtime exception.

To handle this scenario, let us modify the above script as shown below:

String[] countryNames = new String[5];
// Try block
try
{
&nbsp;&nbsp; &nbsp;countryNames[0] = 'India';
&nbsp;&nbsp; &nbsp;countryNames[1] = 'Cyprus';
&nbsp;&nbsp; &nbsp;countryNames[2] = 'Canada';
&nbsp;&nbsp; &nbsp;countryNames[3] = 'Austria';
&nbsp;&nbsp; &nbsp;countryNames[4] = 'Mauritius';

&nbsp;&nbsp; &nbsp;for(int idx=0; idx&amp;lt;=5; idx++)
&nbsp;&nbsp; &nbsp;{
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;com.eviware.soapui.SoapUI.globalProperties.setPropertyValue
( &amp;quot;CountryName&amp;quot;, countryNames[idx]);

&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;def testStep = testRunner.testCase.testSteps['GetCitiesByCountry'];
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;testStep.run(testRunner,context);

&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;log.info('Executed at ' + idx + ' times!');
&nbsp;&nbsp; &nbsp;}
}
catch(Exception exp) // Catch the exception and displaying the message in the log
{
&nbsp;&nbsp; &nbsp;log.info('You are trying to access invalid array index. Please check and try again!');
}

Here is the result for the above script.

Exception Handling in Groovy Scripts 5

This is how we can effectively handle runtime exceptions during our program execution.

Note: we can use ArrayIndexOutOfBoundsException in the “catch” block directly instead of using Exception class. If we put the exact exception name in the “catch” block”, it will catch only when the particular exception is thrown. If any other pre-defined exceptions are thrown, the catch block will fail.

A good automation script should have proper exception handlers. Otherwise, it will be difficult to monitor every moment of the execution.

As I have mentioned earlier, a groovy script supports “throws” keyword to throw the pre-defined exception to the caller.

Look at the the sample script below to understand the concept:

<return-type> <method name> [ arguments / parameters ] throws <exception name>
{
                <statements to be executed>
}

Here’s the sample code for the above skeleton.

// Invoke Method
MethodWithThrowKeyword();

void MethodWithThrowKeyword() throws ArrayIndexOutOfBoundsException
{
&nbsp;&nbsp; &nbsp;String[] countryNames = new String[5];

&nbsp;&nbsp; &nbsp;countryNames[0] = 'India';
&nbsp;&nbsp; &nbsp;countryNames[1] = 'Cyprus';
&nbsp;&nbsp; &nbsp;countryNames[2] = 'Canada';
&nbsp;&nbsp; &nbsp;countryNames[3] = 'Austria';
&nbsp;&nbsp; &nbsp;countryNames[4] = 'Mauritius';

&nbsp;&nbsp; &nbsp;for(int idx=0; idx&amp;lt;=5; idx++)
&nbsp;&nbsp; &nbsp;{
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;log.info('Country Names: ' + countryNames[idx]);
&nbsp;&nbsp; &nbsp;}
}

In the above script, the ArrayIndexOutOfBoundsException will be thrown to the called function. There we need to handle it properly with a try-catch block. Otherwise, an exception will be thrown by SoapUI.

Conclusion

Implementing exception handling in our regular web services related testing scripts will be helpful for us to maintain the code and reduce manual intervention/monitoring by testers. You can use multiple try-catch blocks when required in the script.

Next Soap UI tutorial #12: We will provide more information and features of SoapUI Pro version.

So keep reading. Your feedback, questions, and suggestions are always welcome. Post them in the comments section below. We would love to hear your thoughts.

Was this helpful?

Thanks for your feedback!

Recommended Reading

8 thoughts on “How to Handle Exception in SoapUI Groovy Scripts – SoapUI Tutorial #11”

  1. how can we use this concept if some assertion fails in scriptassertion file? i want to call other steps to clean test data from catch block . if some assertion fails in the middle of test case , readyapi is exiting the execution of that test . any idea?

    Reply
  2. I tried to use a try() block when open a file that doesn’t exists in a Dispatch SCRIPT (mockservice response) as:

    try{
    file = new File (groovyUtils.projectPath + ‘file’)
    }
    catch(Exception ex)
    {
    // other action
    }

    but mockresponse always returns

    Failed to dispatch using script; java.io.FileNotFoundException: ….

    and never “the other action” in catch block

    any suggestion?

    Reply
    • ya lo resolví, el try() no debía hacerse a la hora de construir el file = new File(), el try() debía estar cuando intentara usar file, como en file.text

      Reply
  3. Tutotrial is as good as all other in this series

    2 changes i would like you to make

    1) Please include the link for the web service, in current tutorial Globalweather WSDL link is missing , i google to get ‘GetCityByCountryCode’ link

    2) When you say ‘next tutorial’ please give a hyperlink otherwise we need to goto the main page of SOAP series

    Reply

Leave a Comment