如何访问trait中的私有方法

时间:2015-04-20 15:51:18

标签: groovy

我想在单元测试中访问特征中的私有方法,但我无法弄清楚如何去做。

我有以下测试代码:

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

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

我在这个例子中想要实现的是访问私有方法并打印出“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)

如何访问私有方法?

2 个答案:

答案 0 :(得分:2)

你不能,as the documentation says

  

Traits也可以定义私有方法。这些方法不会出现在特质合同界面中:

你应该可以从其他,公共特征方法或特征中的静态方法中调用它们,例如:

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

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

答案 1 :(得分:1)

我发现如何在不改变特性的情况下调用私有方法,让类实现它然后调用它:

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

class SomeClass implements YellTrait {
}

println new SomeClass().yell()

可以想象,您可以让您的单元测试类实现该特征,然后直接调用私有方法。