繁体   English   中英

如何模拟没有返回值的方法是Option [SomeCaseClassDefinedInsideThisClass]的方法的返回

[英]How to mock return of None of method which return type is Option[SomeCaseClassDefinedInsideThisClass]

我希望该测试能够通过:

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代码,我会说该模拟并不是OO意义上的FruitImpl的真实派生。 其目的是允许方法拦截,因此仅处理Facade 随之而来的是,该模拟实际上没有定义与路径相关的类型FruitName ,因此无法使用依赖于该方法的方法签名。

这就是为什么当FruitName定义从FruitImpl移出时它确实起作用的FruitImpl 现在,它独立于模拟程序而存在,模拟程序依赖于该模拟程序,然后按预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM