SOAPUI 5.4.0执行Groovy脚本触发java.lang.InstantiationException错误求助
嘿,我来帮你搞定这个SOAPUI Groovy脚本的问题!
你碰到的groovy.lang.GroovyRuntimeException,核心原因其实很明确:你的MyClass只定义了带log, context, testRunner三个参数的构造函数,但在Call类里实例化它的时候,用了无参的new MyClass()。从错误堆栈里的Caused by: java.lang.NoSuchMethodException: MyClass.<init>()就能看出来——JVM找不到MyClass的无参构造方法,自然没法创建实例。
另外,SOAPUI 5.4.0的Groovy执行引擎比旧版本更严格,旧版本可能对这种不规范的实例化有宽松处理,但新版本完全遵循标准Groovy/Java的规则,所以旧脚本在新版本就报错了。
根据你的需求,我整理了两种修复方式:
方案1:保留类结构,正确传参
如果你想保留现有的类封装逻辑,只需要在实例化MyClass时,把SOAPUI脚本里默认就能用的log, context, testRunner传进去就行,另外稍微调整下Call类的代码结构,避免在类定义块里直接执行逻辑:
class MyClass { // 三个必填字段 def log def context def testRunner public MyClass(log, context, testRunner) { this.log = log this.context = context this.testRunner = testRunner } def myMethod() { log.info "Reference Groovy function file" } } class Call { def run() { // 传入SOAPUI自带的三个内置变量 MyClass myClass = new MyClass(log, context, testRunner) myClass.myMethod() } } // 调用Call类的执行方法 new Call().run()
方案2:简化脚本,直接用内置变量
要是你只是想复用方法,其实完全没必要搞这么多类——SOAPUI的Groovy脚本里本来就可以直接用log, context, testRunner,直接写方法调用就行,简洁又不容易出错:
def myMethod() { log.info "Reference Groovy function file" } // 直接调用方法 myMethod()
不管选哪种方案,执行后你都能在SOAPUI的日志面板里看到Reference Groovy function file的输出,再也不会碰到那个实例化异常啦。
内容的提问来源于stack exchange,提问作者Error Hunter

