All about SOAP UI and Groovy in it

Posts tagged ‘loop in groovy’

Looping in Groovy Step

While testing several conditions or performing the same operations over a range of values, we intend to use loops. We have three ways to accomplish looping in a groovy step.

1)      while

2)      for

3)      closures

For developers ‘while’ and ‘for’ are familiar operations.

while

Usage:  while (condition) {

// useful code here, which keeps executing until the condition is true

}

Example:

def a = 3;

while (a > 0) {

a- -;

log.info(‘ more ‘ + a + ‘ loop(s) left’);

}

for

Usage: for (x in <some range of values>) {

// useful code here, which executes till the iteration over range of values is complete

}

Example:

for ( ad in 0..9) {

log.info(ad + ‘ inside’);

}

For more usages of ‘for’ loop click here.

closures

closures are similar to iterators. We mention an array or map of values, and write a closure to iterate over it.

To access the current value in the loop ‘it’ is to be used (but not ${it})

Usage/Example:

def  sampleArray = [“dev”, “integration”, “qa”, “prod”];

def a = 1;

sampleArray.each() {

log.info(a + ‘:’ + it);

a++;

}

If you have a map to iterate in groovy step like below

def sampleMap = [ “Su” : “Sunday”, “Mo” : “Monday”, “Tu” : “Tuesday”,

“We” : “Wednesday”, “Th” : “Thursday”, “Fr” : “Friday”,

“Sa” : “Saturday” ];

then use

stringMap.each() {

log.info(it);

log.info( it.key + ‘:’ + it.value );

}

Note: break and continue statements can be used only in for and while loops but not in a closures.

So if you wish to conditionally come out of the loop, its better you use for or while.

(break – as and when encountered comes out of the loop completely;

continue – as and when encountered, skips all the succeeding steps in the loop and starts with next iteration. )

(Please feel free to get back if u have any trouble…as i’m just a mail away…otherwise leave a comment)