gpt4 book ai didi

scala - 如何在 Scala 中测试私有(private)类方法?

转载 作者:行者123 更新时间:2023-11-28 19:38:46 36 4
gpt4 key购买 nike

我有一个带有私有(private)方法的伴生对象,如下所示:

package com.example.people

class Person(val age: Int)

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

我想测试这个方法,像这样:

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

}

对于让测试代码访问私有(private)方法有什么帮助吗?

实际上,正如所写的那样,我可以创建 Person 的子类,但是如果 Person 被声明为 final 会怎样还是密封

谢谢!

最佳答案

在测试所有内容时,我处于中间位置。我通常不会测试所有内容,但有时能够对私有(private)函数进行单元测试非常有用,而不必破坏我的代码以使其成为可能。如果您使用的是 ScalaTest,则可以使用 PrivateMethodTester 来完成。

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

这可能不是您想要做的,但您明白了。

关于scala - 如何在 Scala 中测试私有(private)类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21369093/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com