我希望这个测试能通过:
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
class FruitImpl {
case class FruitName(name: String)
def getFruitName: Option[FruitName] = {
Some(FruitName("apple"))
}
}
class FruitSpec extends FlatSpec with Matchers with MockFactory {
val f = mock[FruitImpl]
(f.getFruitName _).expects().returning(None)
behavior of "getFruitName method"
it should "return None" in {
f.getFruitName should === (None)
}
}
但它失败了:
[error] my/path/QuestionTest.scala:13: overriding method getFruitName in class FruitImpl of type => Option[this.FruitName];
[error] method getFruitName has incompatible type
[error] val f = mock[FruitImpl]
[error] ^
不过,这是有效的:
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
case class FruitName(name: String)
class FruitImpl {
def getFruitName: Option[FruitName] = {
Some(FruitName("apple"))
}
}
class FruitSpec extends FlatSpec with Matchers with MockFactory {
val f = mock[FruitImpl]
(f.getFruitName _).expects().returning(None)
behavior of "getFruitName method"
it should "return None" in {
f.getFruitName should === (None)
}
}
唯一的区别是案例类FruitName是在类FruitImpl之外定义的。为什么一个版本的代码失败,而另一个版本没有?应该如何修复第一个示例中的错误?
如果不看ScalaMock代码,我会说mock不是OO意义上FruitImpl
的真正派生。它的目的是允许方法拦截,因此它只处理facade。因此,mock实际上没有路径相关类型FruitName
的定义,因此无法使用依赖于它的方法签名
这正是为什么当FruitName
定义移出FruitImpl
时,确实工作的原因。它现在独立于mock存在,mock的方法签名依赖于它,然后按预期工作。