首页 > 解决方案 > 如何使用 Groovy 在 SoapUI 中评估类似于 classname.methodname 的字符串?

问题描述

我有如下的常规代码:

def randomInt = RandomUtil.getRandomInt(1,200);
log.info randomInt

def chars = (("1".."9") + ("A".."Z") + ("a".."z")).join()
def randomString = RandomUtil.getRandomString(chars, randomInt)   //works well with this code
log.info  randomString


evaluate("log.info new Date()")

evaluate('RandomUtil.getRandomString(chars, randomInt)')   //got error with this code

我想使用 Groovy 在 SoapUI 中评估一个类似于 {classname}.{methodname} 的字符串,就像上面一样,但是在这里出现错误,如何处理这个问题并让它像我期望的那样工作?

我试过了:

evaluate('RandomUtil.getRandomString(chars, randomInt)')   //got error with this code

错误如下:

Thu May 23 22:26:30 CST 2019:ERROR:An error occurred [No such property: getRandomString(chars, randomInt) for class: com.hypers.test.apitest.util.RandomUtil],有关详细信息,请参阅错误日志

标签: groovy

解决方案


以下代码:

log = [info: { println(it) }]

class RandomUtil { 
  static def random = new Random()

  static int getRandomInt(int from, int to) {
    from + random.nextInt(to - from)
  }

  static String getRandomString(alphabet, len) {
      def s = alphabet.size()
      (1..len).collect { alphabet[random.nextInt(s)] }.join()
  }
}

randomInt = RandomUtil.getRandomInt(1, 200)
log.info randomInt

chars = ('a'..'z') + ('A'..'Z') + ('0'..'9')

def randomString = RandomUtil.getRandomString(chars, 10)   //works well with this code
log.info  randomString


evaluate("log.info new Date()")

evaluate('RandomUtil.getRandomString(chars, randomInt)')   //got error with this code

模拟您的代码,运行,并在运行时产生以下输出:

~> groovy solution.groovy
70
DDSQi27PYG
Thu May 23 20:51:58 CEST 2019

~> 

我组成了 RandomUtil 类,因为您没有包含它的代码。

我认为您看到错误的原因是您定义了变量charrandomInt使用:

def chars = ... 

def randomInt = ...

这会将变量放在本地脚本范围内。请参阅此 stackoverflow 答案以获取说明,其中包含指向将事物放入脚本全局范围的不同方法的文档的链接以及其工作原理的说明。

本质上,您的 groovy 脚本代码隐含地是groovy Script 类的实例,而后者又具有与之关联的隐式Binding 实例。当您编写时def x = ...,您的变量在本地范围内,当您编写x = ...binding.x = ...变量在脚本绑定中定义时。

evaluate方法使用与隐式脚本对象相同的绑定。因此,我上面的示例有效的原因是我省略了defand 只是键入chars =并将randomInt =变量放在脚本绑定中,从而使它们可用于evaluate表达式中的代码。

虽然我不得不说,即使如此,措辞No such property: getRandomString(chars, randomInt)对我来说似乎真的很奇怪......我会预料No such methodNo such property: chars等等。

在这里分享 for 的代码RandomUtil可能会有所帮助。


推荐阅读