GroovyShell脚本需要调用本地方法

krcsximq  于 2023-02-03  发布在  Shell
关注(0)|答案(1)|浏览(130)

我需要从一个String创建一个Script,并在当前测试类的上下文中执行它。

import spock.lang.Specification

class MyTestSpec extends Specification {
    Integer getOne() { return 1 }
    Integer getTwo() { return 2 }

    void 'call script with local methods'() {
        given:
        GroovyShell shell = new GroovyShell()
        Script script = shell.parse("getOne() + getTwo()")

        when:
        def result = script.run()

        then:
        result == 3
    }
}

这会产生以下错误:

No signature of method: Script1.getOne() is applicable for argument types: () values: []

我看到可以使用shell.setProperty来设置变量,但是如何将方法的实现传递给脚本呢?

kg7wmglp

kg7wmglp1#

当然,我一贴出这个,就找到了我的答案。

import org.codehaus.groovy.control.CompilerConfiguration
import spock.lang.Specification

class MyTestSpec extends Specification {
    Integer getOne() { return 1 }
    Integer getTwo() { return 2 }

    void 'call script with local methods'() {
        given:
        CompilerConfiguration cc = new CompilerConfiguration()
        cc.setScriptBaseClass(DelegatingScript.name)
        GroovyShell sh = new GroovyShell(this.class.classLoader, new Binding(), cc)
        DelegatingScript script = (DelegatingScript) sh.parse("getOne() + getTwo()")
        script.setDelegate(this)

        when:
        def result = script.run()

        then:
        result == 3
    }
}

相关问题