如何在Groovy中使用if else语句?

kir*_*las 9 groovy

我正在使用Soapui的Groovy步骤.以下代码运行良好但似乎很长且重复:

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")
Run Code Online (Sandbox Code Playgroud)

是否可以在一次测试中执行相同操作,而不是在每一行上重复IF和ELSE.我试过TRY CATCH,但我不能有错误的堆栈跟踪.

任何人都可以帮助减少代码.谢谢

Mic*_*urd 10

由于字段各不相同,您仍需要进行每项检查,但更简洁的形式是:

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")
Run Code Online (Sandbox Code Playgroud)

通过更多努力,您可以减少重复,但可能会使代码更难以阅读.例如

log.info "bucket ${response.comp.bucket[3] == null ? '=' : 'is not'} null"
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,至少在这种情况下,第二种形式更难以阅读.


nap*_*011 4

我不知道这是否是您的偏好,但您可以使用switch而不是使用长if..else语句,例如:

def x = response.comp.type[3]
switch(x){
  case "value1" : log.info("value1 is present")
  ...
  default: log.info("value is not present")
}
Run Code Online (Sandbox Code Playgroud)

其中x是您要分配给它的值。response.comp.bucket[]对和做同样的事情response.comp.cycle[]

编辑

我修改了代码,将 x 声明为 response.comp.type[3] 的持有者,并检查它是否具有“value1”。