问题描述
我有一个带有私有方法的伴生对象,如下所示:
I have a companion object with a private method, like so:
package com.example.people
class Person(val age: Int)
object Person {
private def transform(p: Person): Person = new Person(p.age + 1)
}
我想测试这个方法,比如:
I would like to test this method, with something like:
class PersonSpec extends FlatSpec {
"A Person" should "transform correctly" in {
val p1 = new Person(1)
val p2 = Person.transform(p1) // doesn't compile, because transform is private!
assert( p2 === new Person(2) )
}
}
让测试代码访问私有方法有什么帮助吗?
Any help on having test code access private methods?
实际上,正如它所写的那样,我可能能够创建 Person
的子类,但是如果 Person
被声明为 final
还是密封
?
Actually, as it is written, I might be able to create a subclass of Person
, but what if Person
is declared as final
or sealed
?
谢谢!
推荐答案
在测试所有内容时,我处于中间状态.我通常不会测试所有内容,但有时能够对私有函数进行单元测试而不必修改我的代码使其成为可能真的很有用.如果您使用的是 ScalaTest,则可以使用 PrivateMethodTester 来完成.
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.
这篇关于如何在 Scala 中测试私有类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!