How to test trait private methods

1,445 views
Skip to first unread message

kgrodzicki

unread,
Jun 28, 2010, 9:49:14 AM6/28/10
to scalatest-users
Hi,
I am trying to test private methods which are inside of some
trait(using PrivateMethodTester). Is there possible to do it? I always
get
"""
java.lang.IllegalArgumentException: Can't find a private method named:
privateTest
at org.scalatest.PrivateMethodTester
$Invoker.invokePrivate(PrivateMethodTester.scala:229)
at com.kgrodzicki.fishing.e.BoatsTest.testFillBunker(BoatsTest.scala:
59)
"""
Testing private methods which are inside of class works like a charm.

I am using:
- scala-library 2.8.0.RC6
- scalatest 1.2-for-scala-2.8.0.RC6-SNAPSHOT

Thanks for help!
Krzysztof

Bill Venners

unread,
Jun 28, 2010, 6:37:30 PM6/28/10
to scalate...@googlegroups.com
Hi Krzysztof,

Private methods in traits end up as static methods in a synthetic
class generated by the Scala compiler, with a name formed by adding
"$class" to the trait name. So that's a bit more difficult to use
reflection to test. There are some options, which are described in the
ScalaDoc for PrivateMethodTester:

One limitation to be aware of is that you can't use
PrivateMethodTester to test a private method declared in a trait,
because the class the trait gets mixed into will not declare that
private method. Only the class generated to hold method
implementations for the trait will have that private method. If you
want to test a private method declared in a trait, and that method
does not use any state of that trait, you can move the private method
to a companion object for the trait and test it using
PrivateMethodTester that way. If the private trait method you want to
test uses the trait's state, your best options are to test it
indirectly via a non-private trait method that calls the private
method, or make the private method package access and test it directly
via regular static method invocations.

ScalaDoc is here:

http://www.scalatest.org/scaladoc/doc-1.0/org/scalatest/PrivateMethodTester.html

> --
> You received this message because you are subscribed to the Google
> Groups "scalatest-users" group.
> To post to this group, send email to scalate...@googlegroups.com
> To unsubscribe from this group, send email to
> scalatest-use...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/scalatest-users?hl=en
> ScalaTest itself, and documentation, is available here:
> http://www.artima.com/scalatest
>

Thanks.

Bill
----
Bill Venners
Artima, Inc.
http://www.artima.com

Reply all
Reply to author
Forward
0 new messages