Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if else statement with Groovy?

Tags:

groovy

i'm using a Groovy step with Soapui. The following code is working well but it seems to be long and repetitive:

if(response.comp.type[3] == "value1")
log.info ("value1 is present")
else
log.info ("value1 is not present")

if(response.comp.bucket[3] == null)
log.info ("bucket = null")
else
log.info ("bucket is not null")

if(response.comp.cycle[3] == "new")
log.info ("settings cycle = new")
else
log.info ("settings cycle is null")

Is it possible to do the same in one test instead of repeating the IF and ELSE on each line. i tried with TRY CATCH but i cannot have the stack trace of the error.

Can anyone help to reduce the code. Thank you

like image 857
kirk douglas Avatar asked Dec 10 '14 03:12

kirk douglas


1 Answers

As the fields are all different you still need to do each check but a more concise form would be:

log.info (response.comp.type[3] == "value1" ? "value1 is present" : "value1 is not present")
log.info (response.comp.bucket[3] == null ? "bucket = null" : "bucket is not null")
log.info (response.comp.cycle[3] == "new" ? "settings cycle = new" : "settings cycle is null")

With a little more effort you could reduce duplication but at the risk of making the code more difficult to read. E.g.

log.info "bucket ${response.comp.bucket[3] == null ? '=' : 'is not'} null"

As you can see, in this case at least, the second form is harder to read.

like image 170
Michael Rutherfurd Avatar answered Oct 01 '22 23:10

Michael Rutherfurd