请记住,如果将它们提升为函数,则可以模拟an的方法。object
case class Person(name: String)
object Person {
def listToJson(lp: List[Person]) = "some actual implementation"
}
class ClassUnderTest(listToJson: (List[Person]) => String = Person.listToJson(_)) {
def testIt(lp: List[Person]) = listToJson(lp)
}
import org.specs._
import org.specs.mock.Mockito
import org.mockito.Matchers._
class ASpec extends Specification with Mockito {
"a thing" should {
"do whatever" in {
val m = mock[(List[Person]) => String]
val subject = new ClassUnderTest(m)
m(Nil) returns "mocked!"
subject.testIt(Nil) must_== "mocked! (this will fail on purpose)"
}
}
}
在这里,我不是在嘲笑对象 Person,而是在嘲笑对象上的方法(这可能是 OP 的意图)。
测试结果显示了 mocking 工作:
[info] == ASpec ==
[error] x a thing should
[error] x do whatever
[error] 'mocked![]' is not equal to 'mocked![ (this will fail on purpose)]' (ASpec.scala:21)
[info] == ASpec ==
同时,生产时的使用ClassUnderTest
只是new ClassUnderTest
因为注入的函数是默认参数。