In this particular lesson on SoapUI, our focus will be on managing exceptions via Groovy scripting. Despite the similarity between Groovy and Java in handling runtime exceptions, owing to the integration of Java libraries, we will delve deeply into the foundational principles in SoapUI and the nitty-gritty of exception management in Java.
This is the 11th lesson in our SoapUI tutorial series. This marks the culmination of the free version of SoapUI tutorial series. Yet, a few subjects remain in this series, including topics on SoapUI pro features, the usage of REST and SOAP services, as well as data-driven testing in SoapUI.
Recommended IPTV Service Providers
- IPTVGREAT – Rating 4.8/5 ( 600+ Reviews )
- IPTVRESALE – Rating 5/5 ( 200+ Reviews )
- IPTVGANG – Rating 4.7/5 ( 1200+ Reviews )
- IPTVUNLOCK – Rating 5/5 ( 65 Reviews )
- IPTVFOLLOW -Rating 5/5 ( 48 Reviews )
- IPTVTOPS – Rating 5/5 ( 43 Reviews )
Firstly, let’s provide a concise overview of exceptions:
What exactly is an exception?
An exception denotes an error that surfaces during the execution of a program. It is caused by various factors such as illegal data, network connection loss, attempts to open missing files, accessing nonexistent classes, memory leakages (compelling the system to function with extensive amounts of data), unresponsive database servers, etc. Both users, developers, and hardware components can cause these errors.
In the backdrop, whenever an exception surfaces during execution, SoapUI attempts to locate a handler. This block, which contains the exception-catching code, is referred to as the handler.
Exceptions can basically be sub-divided into two categories:
- Runtime exception
- Compilation-time exception – non-relevant to SoapUI since it doesn’t contain an explicit compiler
The screenshot below shows a runtime exception caused by invalid code. In the script shown, we attempt to divide a whole number by zero. The error message in the dialog box reveals that the exception is precipitated by the Java libraries and the error message reads Division by zero.
We have the capability to intercept this exception during execution and manage it programmatically. But before that, let’s first comprehend some vital terminology used in Java exception theories. These terms can also be applied in Groovy scripts. They consist of:
- Throw – It enables us to manually instigate an exception, i.e., to throw exceptions defined by the user.
- Throws – It can invoke predefined exceptions from the method definition. In the event of a runtime error during execution, it will intercept the exception.
- Try and Catch – The “try” term is paired with the “catch” term. If we can predict the portion of the program where an exception could occur during execution, we can leverage the “try” block in that location. Immediately after the “try” block, the “catch” block should commence in order to wedge the exception. Inside the catch block, we must compose the handler for exception management.
- Finally – This term denotes the default and optional block in the exception structure. If we require any statements to be executed at the conclusion of the program, such as cleaning unused objects or closing connections, they can be implemented in this block.
The structure of an exception typically follows this pattern:
try
{
<code to be executed>
}
catch <exception name>
{
<exception handler>
}
finally
{
<default statements>
}
Let’s now aim to actualize the exception handler in the sample code that we previously saw in the screenshot.
Introduce a new test suite under the GlobalWeather project. Following this, add a test case and a Groovy script test step under the test step. In the script editor, enter the following code.
// Variable initialization int a = 10; int b = 0; // try-catch section try { // Division of a number by zero int c = a/b; log.info('Result :' + c); } catch(Exception expObj) { // Handling the exception log.info('You are attempting to divide ' + a + ' by ' + b + '. This operation is not feasible!'); }
The script above yields the result as depicted in the following screenshot.
As mentioned earlier, we attempted to divide “A” by “B” where B equals zero. Consequently, the ‘catch’ block gets executed and displays the custom message in the log. It’s critical to note that in the “catch” statement, we have utilized the Exception class, which serves as the superclass in Java for all embedded exceptions. All built-in exception classes are derived from the Exception class. To handle unpredictable runtime exceptions, we can use the Exception class in the “catch” block.
Let’s now alter the script above to yield the expected result. Refer to the next screenshot:
Let’s now test this in our standard web services testing. In the script that follows, we have refrained from using the try-catch block, resulting in a runtime exception.
// Array initialization 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 script above will result in an ArrayIndexOutOfBoundsException because it tries to access a non-existent array index i.e., 5 which is not present.
(Click on the image to zoom in)
As observed in the script above, we have allocated the “countryNames” array a size of five. This implies that it only accepts five string values, i.e., names of countries. Within the iteration commands, we have verified idx <= 5. Thus the loop iterates six times and attempts to locate the 6th element in the array, which does not exist. Consequently, a runtime exception is precipitated.
To manage this scenario, let’s revise the script above as follows:
String[] countryNames = new String[5]; // Try section 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 ' + idx + ' times!'); } } catch(Exception exp) // Intercept the exception and reveal the message in the log { log.info('You are attempting to access an invalid array index. Please verify and retry!'); }
Below is the outcome for the script above.
That is how we can manage runtime exceptions during software execution.
Attention: We can directly incorporate ArrayIndexOutOfBoundsException into the “catch” section instead of employing the Exception class. If we pinpoint the precise exception name in the “catch” block, it will exclusively intercept that particular exception. If any other built-in exception is instigated, the catch block will not function.
An efficient automation script should have sufficient exception handlers to simplify monitoring every progression of the execution.
As stated earlier, Groovy scripting supports the “throws” keyword to instigate predefined exceptions to the caller.
Here’s an example script to grasp this concept:
<return-type> <method name> [ arguments / parameters ] throws <exception name>
{
<statements to be performed>
}
Here’s the sample code for the structure above.
// Invoking the 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 script above, the ArrayIndexOutOfBoundsException gets thrown to the invoked function. However, we are required to manage it properly with a try-catch block; otherwise, SoapUI will instigate an exception.
Summary:
Incorporating exception handling into our routine web services related testing scripts will help us upkeep the code and lessen manual interaction/overseeing by testers. When needed, we can integrate multiple try-catch blocks into the script.
Coming up in the next SoapUI lesson #12: We’ll share more details and features of the SoapUI Pro version in our next lesson.
Keep reading. As always, all thoughts, queries, and recommendations are welcomed!