The previous SoapUI tutorials have been an introduction into SoapUI and its programming concepts. We will from now on move into more advanced Groovy scripting concepts. Let us being this with Conditional flow statements – both Boolean and iterative statements. Then we will move on to arrays collection.
This is the 9th tutorial in our SoapUI tutorial series.
Conditional statements are used to control the flow of the execution. Here are different types of conditional statements in Groovy.
What You Will Learn:
#1. Control or logical statements:
These statements result in true or false based on the logical conditions. They are AND, OR and NOT. The symbols used are ‘&& (and)’, ‘|’| and ‘! (Exclamation)’ respectively. The behavior is as mentioned in the truth table:
“And” Operator truth table:
“OR” operator truth table:
“NOT” operator for negation purpose
Conditional statement: programming languages support the following conditional statements:
- If…else statement
- If…else if…else statement
- Ternary operator
- Switch statement
A) if…else block syntax:
if <condition>
{
<Statements to be executed>
}
Else
{
<default statements>
}
In this syntax, when <condition> meets true the given statement will get executed. We need to enclose the statements by curly braces if the block contains more than one line. This instructs the entire block should execute based on the condition.
Look at the example code snippet.
int a=100 int b=200 if (a>b) { log.info('B is greater than A'); <To Do> } else { log.info('A is greater or both are equal'); <To Do> }
An if…else… statement should contain only one ELSE block.
B) Multiple conditional blocks: if…else if…else syntax
if <condition1>
{
<Statements to be executed>
}
Else if <condition2….n>
{
<Statements to be executed>
}
Else
{
<default statements>
}
If…else if…else statement is little different than if…else… statement- in terms that it has else if block. This block is used for adding multiple conditions. Look at the following example.
int a=100 int b=200 int c=300 if (a>b && a>c) { log.info('A is greater than B and C'); } else if (b>a && b>c) { log.info('B is greater than A and C'); } else { log.info('C is greater than A and B or All are equal numbers'); }
And look at the output screenshot for the above script: Also, please use this as a reference for the boolen operator example too:
C) Ternary operator:
This operator works similar to if…else statement. It has two operands such as question mark (TRUE) and colon for FALSE / default statements.
def A = 100
def B = (A > 100) ? “PASS” : “FAIL”
log.info(B)
Here’s the screenshot for the above script.
D) Switch case: This statement allows multiple conditional branches with different values. Also it supports comparison of class object references, regular expressions, collections such as arrays, lists etc.
Switch <value>
{
case <match1>:
<execute block>;
break;
case <match1…match (n)>:
<execute block>;
break;
default:
<execute default block>;
}
The case statements compare the values with the switch case value. If it’s a match, then the corresponding case block gets executed. Once the block is executed then it should be stopped by the “break” keyword. If we missed “break” keyword at end of the case statement, execution will be moved to next case statement- and that might not be necessary. In case none of the cases are true, default block will be executed. Please note that Groovy supports all the major operators and keywords as it is incorporated with the java libraries.
def country="India" switch(country) { case "Japan": log.info('Country matched with 1st case statement'); break; case "Australia": log.info('Country matched with 2st case statement'); break; case "India": log.info('Country matched with 3st case statement'); break; default: log.info('None of the matches available :('); }
Here’s the output screenshot for the above script.![]()
#2. Looping or Iterative Statements:
These enable repetition whenever we need and are especially useful for data driven testing.
For instance, let us assume we have a few zip codes in an excel file. To retrieve all the zip codes one by one from the excel file, and pass it to service i.e. GetSuppliersZipcode, we can use iterative statements. SoapUI also provides an alternative feature called data source and data source loop test steps.(Available only in SoapUI Pro trial and licensed versions.)
We can use these following iterative statements in the groovy script:
- For loop
- While loop
For loop:
for (<initialization>; <condition>; <increment /decrement>)
{
<Execute Statements>;
}
In the above syntax, initialization denotes starting point of the loop and based on the condition loop will continue or stop the execution.
See the below script
for(int i=1; i<=10; i++)
{
log.info(‘Loop Iterated ‘ + i + ‘ times’);
}
Above script will produce the results as shown in the following screenshot.
Now let us use control statement and iterative statement in our real testing world. Follow the below steps:
- Add Testcase with your desired name. I have created as “T9_GetSupplierByZipCode_TestCase”.
- Then add a property named “Property_Zipcode”
- Add Test Request step for “GetSupplierByZipCode” service and put the property name in the request as shown in the screenshot.
Add groovy script test step as shown in the following screenshot.
In the groovy script editor, write the following script.
for (int zipCode=1; zipCode<10; zipCode++) { testRunner.testCase.testSteps['Properties']. setPropertyValue('Property_Zipcode', '3000' + zipCode ) def testStep = testRunner.testCase.testSteps['GetSupplierByZipCode']; if (zipCode>5) { log.info('**************Stopped Execution*************'); break; } testStep.run(testRunner,context); log.info('Executed ' + zipCode + ' times') }
The following result is received in the log as well as in the service response screen.
(Click image for enlarged view)
“while” loop:
Syntax:
while <condition>
{
<Execute Statements>;
}
The above logic can be implemented using the “while” loop too.
Hence, the gist is that iterative statement can be used to:
- Execute the test cases or test steps repeatedly
- Control the flow of the execution through the control statements.
#3. Arrays Collection:
Array collection helps store multiple values in a single variable or object. Array index starts at zero by default and we need to use that index with array name to access the corresponding value stored in the array. Syntax to declare arrays in groovy script:
arrayName = new Object[5] or,
arrayName = new Object[10][] or,
arrayName = new Object[10][10][]
Note: While declaring arrays we must specify the initial size otherwise it will throw a compile error. Here’s the simple example for the single dimensional array.
ArrayObj = new Object [5];
ArrayObj[0] = “Testcase1”;
ArrayObj[1] = “Testcase2”;
ArrayObj[2] = “Testcase3”;
ArrayObj[3] = “Testcase4”;
ArrayObj[4] = “Testcase5”;
Now let us implement this in our regular test steps. So add property, test request and script test step under the project test suite as shown in the following screenshot.
And then double click on the script test step and write the following script.
def MAX_LIMIT = 5 def zipCodes = new Object[MAX_LIMIT] zipCodes[0] = "92704" zipCodes[1] = "99362" zipCodes[2] = "31401" zipCodes[3] = "90247" zipCodes[4] = "87102" int i=0; while (i<5) { if (i<5) { testRunner.testCase.testSteps['Properties']. setPropertyValue('Property_Zipcode',zipCodes[i]); def testStep = testRunner.testCase.testSteps['GetSupplierByZipCode']; testStep.run(testRunner,context); log.info('Loop executed ' + i + ' times'); } i++; } log.info("Testcase execution is completed....");
In this script, we initialized array object as 5 and assigned five zip codes in each array location respectively. Next part of the script is iterative block. Here we iterate the loop up to 5 times. Each time array value will be assigned to the property and then move to GetSupplierByZipCode web service to pass this array value in the request. After that, service step will be executed with the zip code. Finally we will get the following message in the log as shown in the screenshot.![]()
So arrays are very useful to handle multiple elements with different types. More practice will foster better understanding and ease of use.
Conclusion
That was an overall introduction with examples to conditional or logical blocks that include IF…ELSE, switch and ternary statements. These statements are controlled by the logical operators such as AND, OR, NOT. When compared to “switch” block “if” block is fast and simple. To handle multiple collections like arrays to iterate the testing process, loop statements are critical.
Next SoapUI tutorial #10: In next post we will learn “Object-Oriented Groovy Scripting in SoapUI”.
More useful concepts are coming up in the next SoapUI Groovy Script tutorials. Keep reading and please share your experiences and queries in the comments below.
Hi these are very informative tutorials.
@Sourabh Shukla: Thank you for positive feedback and appreciation!
where can we see all the executions happened for the API for all different values (30001-30005)
By mistake i started an infinite loop, how to stop that ? i forgot to put i++ ? i read online i think only way is to close soap UI
i tried that for loop though groovy ran successfully but i was not able to see the output of all 5 executions which happened with different values
also please share some technical details for the steps like
testRunner.testCase.testSteps[‘Properties’].
setPropertyValue(‘Property_Zipcode’,zipCodes[i]);
its useful in understanding
Very Helpful!.
Thank you.
Hi guys I have below scenario please help me
step 1. generate random number in groovy script step 2. connect to database step 3. verify whether generated random number exist in database or not(check in all rows) if random number exist stop execution else continue execution
Very helpful! Thank you so much!
Very useful information. I am enjoying the learning.
Thank you so much for your efforts. Keep up the good work.
//It worked for me
${#TestCase#zipcode}
___________________________________________
log.info(“Starting the execution”);
for (int zipCodeCounter=1; zipCodeCounter<10; zipCodeCounter++)
{
testRunner.testCase.setPropertyValue("zipcode", "1000" + zipCodeCounter )//Replacing the property value with each iteration
def testStep = testRunner.testCase.testSteps["GetSupplierByZipCode"]//assigning the SOAP request to the teststep variable
testStep.run(testRunner,context);//running the SOAP request in every iteration
log.info('Executed ' + zipCodeCounter + ' times')
}
log.info ("Execition completed");
I want to perform a load testing of a web-service using SOAP UI(not the pro version). The reference number field needs a unique value each time. How to do parameterized testing by providing a new reference no. each time a request is fired?