您不能模拟对象中的方法。而且你不应该在你正在测试的类中模拟方法(如果看起来你需要,这是违反单一责任原则的明确症状)。
你可以做的是这样的:
trait Api1 {
def method1(
...
): Unit // NB: also, should not really return a Unit: how are you going to test this???
}
trait Api2 {
def method2(...): Unit // See above
}
class Impl2 extends Api2 {
def method2(...) = // Do stuff
}
class Impl1(val api2: Api2) extends Api1 {
def method1(...) = { ... ; api2.method2(); ... }
}
// You should not really need this, but, you can have it if you want
object A extends Impl1(new Impl2)
所以,现在测试这段代码很简单:
describe("Impl2") {
it ("does nothing") {
new Impl2().method2("foo")
// Nothing happens
// this is what I meant: how do you know it worked?
}
}
describe("Impl1") {
it ("does nothinig") {
val a2 = mock[Api2]
doNothing when a2 method2(any)
val fixture = new Impl1(a2)
fixture.method1()
// Again, nothing happens!
verify(a2).nothing("foo")
}