0

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?

1 Answers1

3

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.

Mario Galic
  • 45,265
  • 6
  • 51
  • 87
  • Thanks @Mario, but if I add my tests to package example, wouldn't users of my library be able to access personTest? Is there a way to prevent users from doing so? – finite_diffidence Jul 11 '20 at 11:30
  • 2
    @finite_diffidence Sources under `src/test/scala` should not end up in the packaged/assambled jar. Also note, in general, it is good practice to have tests mirror the package structure of main sources – Mario Galic Jul 11 '20 at 11:40