groovy - 如何使用 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],有关详细信息,请参阅错误日志
解决方案
以下代码:
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 类,因为您没有包含它的代码。
我认为您看到错误的原因是您定义了变量char
并randomInt
使用:
def chars = ...
和
def randomInt = ...
这会将变量放在本地脚本范围内。请参阅此 stackoverflow 答案以获取说明,其中包含指向将事物放入脚本全局范围的不同方法的文档的链接以及其工作原理的说明。
本质上,您的 groovy 脚本代码隐含地是groovy Script 类的实例,而后者又具有与之关联的隐式Binding 实例。当您编写时def x = ...
,您的变量在本地范围内,当您编写x = ...
或binding.x = ...
变量在脚本绑定中定义时。
该evaluate
方法使用与隐式脚本对象相同的绑定。因此,我上面的示例有效的原因是我省略了def
and 只是键入chars =
并将randomInt =
变量放在脚本绑定中,从而使它们可用于evaluate
表达式中的代码。
虽然我不得不说,即使如此,措辞No such property: getRandomString(chars, randomInt)
对我来说似乎真的很奇怪......我会预料No such method
到No such property: chars
等等。
在这里分享 for 的代码RandomUtil
可能会有所帮助。
推荐阅读
- lua - init.lua 中的 WSL 剪贴板 win32yank
- audio - 将一个视频文件的音频同步+合并到另一个
- mysql - Laravel 8 DB 事务:是控制器实例独有的事务还是连接数据库名称独有的事务?
- javascript - Discord Js无法读取未定义的属性标题
- javascript - 在新页面上保留多级导航栏/侧边栏的状态
- linux - 如何将变量附加到 CURL 命令
- python - MWAA:从 requirements.txt 安装 Airflow Google Providers 时遇到问题
- reactjs - 无法使用注入的 JavaScript 重新加载 WebView
- python - 即使我的索引不是日期时间,熊猫也可以滚动启用偏移量
- spring-boot - Flux Reactive Microservice - 一个微服务向其他微服务发出关于背压的信号