Svante
Svante

Reputation: 1069

How to access private method in trait

I would like to access private methods in a trait for unit testing purposes, but I can't figure out how to do it.

I have the following test code:

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

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

What I'm trying to achieve in this this example is to access the private method and print out "YAAAH!", but instead I get:

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)

What can I do to access the private method?

Upvotes: 2

Views: 1040

Answers (2)

Svante
Svante

Reputation: 1069

I found out how to call the private method without changing the trait, by letting a class implement it and then call it:

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

class SomeClass implements YellTrait {
}

println new SomeClass().yell()

Conceivably, you could let your unit test class implement the trait and then call the private method directly.

Upvotes: 1

tim_yates
tim_yates

Reputation: 171184

You can't, as the documentation says:

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

You should be able to call them from other, public trait methods, or static method in the trait, eg:

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

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

Upvotes: 2

Related Questions