我是 Scala 的新手(来自 Java),我喜欢开发 TDD/BDD。所以在了解 Scala 之前,我已经深入研究了 Scalatest。
从您希望尽可能多地进行测试的角度来看,我想知道您认为什么是单元测试的良好访问策略。
假设我有一个我想测试的类 World 和一个不应该知道关于 World 的一切的类 Agent。
package program {
package world {
class World {
private var notForAgent
def forAgentDuringActing
// forAgentDuringActing has an important side effect in notForAgent
}
}
package agent {
class Agent
// would call World.forAgentDuringActing
}
package world.test {
class WorldSpec extends FunSpec {
describe("The world") {
it("should have side-effect behaviour when the agent acts on it") {
// ... the test ...
}
}
}
}
}
请注意,这些包声明对我来说并不神圣。
我真正想要的是 WorldSpec 将类似于 World 的伴随对象,以便它可以测试副作用。
我想也许访问修饰符限定符会有所帮助。我可以说
private[world] notForAgent
,但这确实比我想要的更多。我真正想要的是 private[this, test.WorldSpec] notForAgent
,但我认为不允许使用多个限定符。你会怎么做才能使这个可测试?或者,你能指出我的想法错误的方向吗?
p.s.我知道“从不测试私有(private)”的说法。但我也知道“测试比代码本身更重要。如果需要测试,请更改访问修饰符”的观点。但是,我想避免在这个线程中进行讨论。
最佳答案
如果您问“如何测试私有(private)方法?”,那么 ScalaTest 实际上支持这一点。见 here .
class C {
private def m(x: Int) = x
}
class CTests extends /*any test suite you like*/ with PrivateMethodTester {
val decoratedM = PrivateMethod[Int]('m)
val c = new C
val actual = c invokePrivate decoratedM(4711)
val expected = 4711
actual should be(expected) // this line depends on the test suite you've chosen
}
关于unit-testing - Scala - 单元测试设置(使用访问修饰符限定符?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10984226/