How can a private class method be tested in Scala?

I am in the middle when it comes to testing everything. I don’t usually test everything, but sometimes it’s really useful to be able to unit test a private function without having to mangle my code to make it possible. If you’re using ScalaTest, you can use the PrivateMethodTester to do it.

import org.scalatest.{ FlatSpec, PrivateMethodTester }

class PersonSpec extends FlatSpec with PrivateMethodTester {

  "A Person" should "transform correctly" in {
      val p1 = new Person(1)
      val transform = PrivateMethod[Person]('transform)
      // We need to prepend the object before invokePrivate to ensure
      // the compiler can find the method with reflection
      assert(p2 === p1 invokePrivate transform(p1))
    }
  }

That may not be exactly what you want to do, but you get the idea.

Leave a Comment