groovy - 如何访问特征中的私有(private)方法

标签 groovy

我想访问特征中的私有(private)方法以进行单元测试,但我不知道该怎么做。

我有以下测试代码:

trait SomeTrait {
    private String yell() { "YAAAH!" }          
}

SomeTrait traitInstance = new Object() as SomeTrait
println traitInstance.yell()

在这个例子中我试图实现的是访问私有(private)方法并打印出“YAAAH!”,但我得到的是:

groovy.lang.MissingMethodException: No signature of method: Object15_groovyProxy.yell() is applicable for argument types: () values: []
Possible solutions: sleep(long), sleep(long, groovy.lang.Closure), wait(), every(), find(), dump() at ConsoleScript24.run(ConsoleScript24:7)

如何访问私有(private)方法?

最佳答案

你不能,as the documentation says :

Traits may also define private methods. Those methods will not appear in the trait contract interface:

您应该能够从其他公共(public)特征方法或特征中的静态方法调用它们,例如:

trait SomeTrait {
    private String yell() { "YAAAH!" }          
    String doYell() { yell() }
}

SomeTrait traitInstance = new Object() as SomeTrait
println traitInstance.doYell()

关于groovy - 如何访问特征中的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29752583/

相关文章:

groovy 无法解析 kotlin 类

gradle - Gradle的Groovy语法:项目

grails - 在Hashmap中搜索并返回值

regex - 在 Groovy 中获取 Mac 地址

grails - 不使用 Controller 逻辑的Grails urlMappings操作和 Controller 行为

forms - Grails 具有动态表单的一对多数据绑定(bind)

grails - 我是否需要做一些特殊的事情才能使命令对象在grails中实例化?

grails - Grails:BootStrap.groovy类的编码

grails - 是否有一个 groovy.jar 及其所有依赖项?

xml - Groovy的XMLUtil序列化方法不起作用