|
|
Re: Testing private Methods
|
Posted: Nov 6, 2008 8:23 PM
|
|
Hi Lukas,
An Update: I just checked in a Pimp trait to the trunk that offers a nice syntax for invoking private methods dynamically. It will be in the next release. To use it you mix trait Pimp into your test class. In tests people usually invoke the same method several times, so first you'd create a PrivateMethod instance and store it in a val of the name of the method. The PrivateMethod construct takes a Symbol of the name of the private method and a Class instance representing its result type. You can then invoke the private method by using the "invokePrivate" operator instead of a dot. Here's an example method that uses the trait:
def testDecorateToStringValue() {
val decorateToStringValue = PrivateMethod('decorateToStringValue, classOf[String])
expect("1") { FailureMessages invokePrivate decorateToStringValue(1.toByte) } expect("1") { FailureMessages invokePrivate decorateToStringValue(1.toShort) } expect("1") { FailureMessages invokePrivate decorateToStringValue(1) } expect("10") { FailureMessages invokePrivate decorateToStringValue(10L) } expect("1.0") { FailureMessages invokePrivate decorateToStringValue(1.0f) } expect("1.0") { FailureMessages invokePrivate decorateToStringValue(1.0) } expect("false") { FailureMessages invokePrivate decorateToStringValue(false) } expect("true") { FailureMessages invokePrivate decorateToStringValue(true) } expect("<(), the Unit value>") { FailureMessages invokePrivate decorateToStringValue(()) } expect("\"Howdy!\"") { FailureMessages invokePrivate decorateToStringValue("Howdy!") } expect("'c'") { FailureMessages invokePrivate decorateToStringValue('c') } expect("Hey!") { FailureMessages invokePrivate decorateToStringValue(new AnyRef { override def toString = "Hey!"}) } }
One cool thing is the result of the method invocation will be the result type of the private method, the type represented by the Class instance passed into the 2nd arg of PrivateMethod's constructor. So you need not cast to use the result. In other words, because decorateToStringValue's result type is String, the type of val s here will be inferred to have type String:
val s = FailureMessages invokePrivate decorateToStringValue(false)
|
|