Learn Advanced SoapUI Groovy Scripting Concepts – SoapUI Tutorial #9

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 9, 2024

In this tutorial, we will learn in detail about advanced SoapUI Groovy Scripting Concepts. Let’s get started.

The previous SoapUI tutorials have been an introduction to SoapUI and its programming concepts. We will now move into more advanced Groovy scripting concepts. Let us do this with Conditional flow statements – both Boolean and iterative statements. We will then move on to the 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 the different types of conditional statements in Groovy. 

Learn Advanced SoapUI Groovy Scripting Concepts

SoapUI Groovy Scripting concepts

#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:

CONDITIONAL STATEMENTS IN GROOVY 1

“OR” operator truth table:

CONDITIONAL STATEMENTS IN GROOVY 2

“NOT” operator for negation purposes.

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 with curly braces if the block contains more than one line. This instructs that the entire block should be executed based on the condition.

Look at the example code snippet.

int a=100
int b=200
if (a&amp;gt;b)
{
                log.info('B is greater than A');
                &amp;lt;To Do&amp;gt;
}
else
{
                log.info('A is greater or both are equal');
&amp;lt;To Do&amp;gt;
}

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 a little different than if…else… statement- in terms that it has else if block. This block is used to add multiple conditions. Look at the following example.

int a=100
int b=200
int c=300
if (a&amp;gt;b &amp;amp;&amp;amp; a&amp;gt;c)
{
                log.info('A is greater than B and C');
}
else if  (b&amp;gt;a &amp;amp;&amp;amp; b&amp;gt;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');
}

Also, look at the output screenshot for the above script: Also, please use this as a reference for the boolen operator example too:

CONDITIONAL STATEMENTS IN GROOVY 3

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.

CONDITIONAL STATEMENTS IN GROOVY 4

D) Switch case: This statement allows for multiple conditional branches with different values. It also 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 statement compares 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 the end of the case statement, then the execution will be moved to the next case statement and that might not be necessary.  If none of the cases are correct, the 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=&amp;quot;India&amp;quot;
switch(country)
{
	case &amp;quot;Japan&amp;quot;:
		log.info('Country matched with 1st case statement');
		break;
	case &amp;quot;Australia&amp;quot;:
		log.info('Country matched with 2st case statement');
		break;
	case &amp;quot;India&amp;quot;:
		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.

CONDITIONAL STATEMENTS IN GROOVY 5

#2. Looping or Iterative Statements

They enable repetition whenever required and are especially useful for data driven testing.

For instance, let us assume we have a few zip codes in an excel file. We can use iterative statements to retrieve all the zip codes one by one from the excel file and pass it to service i.e. GetSuppliersZipcode. 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 the 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 the starting point of the loop and based on the condition loop will continue or stop the execution.

See the script below

for(int i=1; i<=10; i++)
{
                log.info(‘Loop Iterated ‘ + i + ‘ times’);
}

The above script will produce the results as shown in the following screenshot.

CONDITIONAL STATEMENTS IN GROOVY 6

Now let us use control statements and iterative statements 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 the Test Request step for “GetSupplierByZipCode” service and put the property name in the request as shown in the screenshot.

CONDITIONAL STATEMENTS IN GROOVY 7

Add the groovy script test steps as shown in the following screenshot.

CONDITIONAL STATEMENTS IN GROOVY 8

In the groovy script editor, write the following script.

for (int zipCode=1; zipCode&amp;lt;10; zipCode++)
{
	testRunner.testCase.testSteps['Properties'].
setPropertyValue('Property_Zipcode', '3000' + zipCode )
	def testStep = testRunner.testCase.testSteps['GetSupplierByZipCode'];

	if (zipCode&amp;gt;5)
	{
		log.info('**************Stopped Execution*************');
		break;
	}
	testStep.run(testRunner,context);
	log.info('Executed ' + zipCode + ' times')
}

The following results are received in the log as well as in the service response screen.
(Click on the image for an enlarged view)

CONDITIONAL STATEMENTS IN GROOVY 9

“while” loop: 

Syntax:

while <condition>
{
                <Execute Statements>;
}

The above logic can also be implemented using the “while” loop too.

Hence, the gist is that iterative statements can be used to:

  1. Execute test cases or test steps repeatedly
  2. 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 a simple example of a single dimensional array.

ArrayObj = new Object [5];
ArrayObj[0] = “Testcase1”;
ArrayObj[1] = “Testcase2”;
ArrayObj[2] = “Testcase3”;
ArrayObj[3] = “Testcase4”;
ArrayObj[4] = “Testcase5”;

Let us now implement this in our regular test steps. So add property, test request and script test steps under the project test suite as shown in the following screenshot.

CONDITIONAL STATEMENTS IN GROOVY 10

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] = &amp;quot;92704&amp;quot;
zipCodes[1] = &amp;quot;99362&amp;quot;
zipCodes[2] = &amp;quot;31401&amp;quot;
zipCodes[3] = &amp;quot;90247&amp;quot;
zipCodes[4] = &amp;quot;87102&amp;quot;

int i=0;
while (i&amp;lt;5)
{
	if (i&amp;lt;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(&amp;quot;Testcase execution is completed....&amp;quot;);
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.

CONDITIONAL STATEMENTS IN GROOVY 11

So arrays are very useful to handle multiple elements with different types. More practice will foster better understanding and ease of use.

Conclusion

This was an overall introduction with examples of conditional or logical blocks that include IF…ELSE, switch and ternary statements. These statements are controlled by logical operators such as AND, OR, NOT. When compared to “switch” block “if” block is fast and simple. It is critical to handle multiple collections like arrays to iterate the testing process and loop statements.

Next SoapUI tutorial #10: In the 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 section below. We would love to hear from you. 

Was this helpful?

Thanks for your feedback!

Recommended Reading

9 thoughts on “Learn Advanced SoapUI Groovy Scripting Concepts – SoapUI Tutorial #9”

  1. 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

    Reply
  2. //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");

    Reply
  3. 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

    Reply
  4. 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?

    Reply

Leave a Comment