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

In this SoapUI tutorial we will look at exception handling using Groovy scripting. Handling runtime exceptions in groovy is similar to Java as the Java libraries are integrated. However we will discuss basic concepts in SoapUI and go into the depth of exception handling in Java.

This is tutorial #11 in SoapUI tutorials series. This is the last tutorial for free version of SoapUI. There are couple of 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 with a brief introduction to exception:

Exception handling in Groovy script

What is an exception?

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

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

Exceptions are categorized 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 a runtime exception for invalid code. In the below script we tried to divide an integer by 0. In the error dialog 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 be used in groovy script also. They are:

  • 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. So it 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 end of the “try” block, “catch” block should start to catch exception. Inside the catch block, we have to write 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 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 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
{
    // Dividing a number by zero
    int c = a/b;
    log.info('Result :' + c);
}
catch(Exception expObj)
{
    // Exception Handler
    log.info('You are trying to divide ' + a + ' by ' + b + '. This is not possible actually!');
}

The above script produces the following result 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. See that in the “catch” statement, we have used Exception class which is the super class in Java for all the built-in exceptions. All pre-defined exception classes are inherited from Exception class. To handle unpredictable runtime exceptions, we can use Exception class in the “catch” block.


Let us now modify the above script to get the required result. See the following screenshot:

Exception Handling in Groovy Scripts 3

Let us now try this in our regular web services testing. In the following script, we did not use try-catch block so we will get 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<=5; idx++)
{
 com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( "CountryName", 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 image for 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 value 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 below:

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

    for(int idx=0; idx<=5; idx++)
    {
        com.eviware.soapui.SoapUI.globalProperties.setPropertyValue
( "CountryName", countryNames[idx]);
    
        def testStep = testRunner.testCase.testSteps['GetCitiesByCountry'];
        testStep.run(testRunner,context);
        
        log.info('Executed at ' + idx + ' times!');
    }
}
catch(Exception exp) // Catch the exception and displaying the message in the log
{
    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 handle runtime exception 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 thrown, catch block will be failed.

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, groovy script supports “throws” keyword to throw pre-defined exception to the caller.

See the below sample script to understand this 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
{
    String[] countryNames = new String[5];

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

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

In the above script, the ArrayIndexOutOfBoundsException will be thrown to the called function. There we need to handle properly with 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. We can use multiple try-catch blocks when required in the script.

Next SoapUI tutorial #12: In the next tutorial, we will provide more information and features of SoapUI Pro version.

So keep reading. Comments, questions, suggestions are welcome, as always!




Recommended reading

5 comments ↓

#1 krishna iva

Thanks for the clear explanation.

#2 Kavita k

hi,
is this same as java exception handling?

#3 Swati Seela

@Kavita k: Yes. Concept wise and implementation wise too(to a certain extent).

#4 Karunagara Pandi

@Kavita: Yes. we can directly use some of the Java classes in Groovy script editor.

#5 Gaurav Khurana

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

Leave a Comment