【问题标题】:Testing a private method with access modifier in Scalatest在 Scalatest 中使用访问修饰符测试私有方法
【发布时间】:2020-11-01 00:21:45
【问题描述】:

我有以下问题。

假设我有以下课程(此处的示例:Link):

package com.example.people

class Person(val age: Int)

object Person {
  private def transform(p: Person): Person = new Person(p.age + 1)
}

所以我有一个包,里面有一个带有私有方法的类。

现在我知道使用 scalatest 我可以做这样的事情。在我的测试文件夹中,我有:

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))
    }
  }

现在,我的问题是,如果我向我的私有方法添加访问修饰符,如下所示(类似于Link 中的答案):

package com.example.people

class Person(val age: Int)

object Person {
  private[example] def transform(p: Person): Person = new Person(p.age + 1)
}

测试抱怨 transform 不再是私有方法。

即使我有一个私有函数的访问修饰符,我是否仍然可以使用私有方法测试器?

【问题讨论】:

  • 如果方法不再是私有的,为什么还需要私有方法测试器?直接调用就行了。
  • 谢谢@Thilo,原因是我的测试套件不在示例包中,但正如下面马里奥所说,我可以将测试添加到包中。
  • 测试应该总是和他们正在测试的类在同一个包中。而且您不需要测试私有方法。

标签: scala unit-testing scalatest private-methods


【解决方案1】:

给定

package com.example.people

class Person(val age: Int)

object Person {
  private[example] def transform(p: Person): Person = new Person(p.age + 1)
}

您只需要确保相应的测试也在example 包中

package example

class PersonTest extends AnyFunSuite {
  test("A Person should transform correctly") {
    val p1 = new Person(1)
    Person.transform(p1)    // transform is now accessible
    ...
    }
  }
}

在这种情况下,不需要PrivateMethodTester,因为private[example] 使example 包的所有成员都可以使用该方法。

【讨论】:

  • 感谢@Mario,但是如果我将测试添加到包示例中,我的库的用户不能访问 personTest 吗?有没有办法阻止用户这样做?
  • @finite_diffidence src/test/scala 下的源不应出现在打包/组装的 jar 中。另请注意,一般来说,让测试反映主要来源的包结构是一种很好的做法
猜你喜欢
  • 2022-11-18
  • 2020-08-23
  • 2017-12-22
  • 2014-08-27
  • 2015-11-26
  • 2011-04-18
  • 2011-01-31
  • 1970-01-01
相关资源
最近更新 更多