I have the following issue.
Suppose I have the following class (example from here: Link ):
package com.example.people
class Person(val age: Int)
object Person {
private def transform(p: Person): Person = new Person(p.age + 1)
}
So I have a package, and inside it I have a class with a private method.
Now I know using scalatest I can do something like this. In my test folder I have:
import org.scalatest.{ FlatSpec, PrivateMethodTester }
class PersonTest extends AnyFunSuite with PrivateMethodTester {
test("A Person" should "transform correctly") {
val p1 = new Person(1)
val transform = PrivateMethod[Person]('transform)
assert(p2 === p1 invokePrivate transform(p1))
}
}
Now, my question is, if I add an access modifier to my private method as follows (similar to the answer in this Link):
package com.example.people
class Person(val age: Int)
object Person {
private[example] def transform(p: Person): Person = new Person(p.age + 1)
}
The test complains that transform is no longer a private method.
Is there a way I can still use the private method tester, even if I have an access modifier for a private function?
Given
package com.example.people
class Person(val age: Int)
object Person {
private[example] def transform(p: Person): Person = new Person(p.age + 1)
}
you just have to make sure that corresponding test is also within example
package
package example
class PersonTest extends AnyFunSuite {
test("A Person should transform correctly") {
val p1 = new Person(1)
Person.transform(p1) // transform is now accessible
...
}
}
}
in which case there is no need for PrivateMethodTester
because private[example]
makes the method available to all the members of example
package.