简体   繁体   English

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

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

I would expect this test to pass: 我希望该测试能够通过:

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)
  }
}

But it fails with: 但是它失败了:

[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]               ^  

This works, though: 这可以,但是:

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)
  }
}

The only difference is that the case class FruitName is defined outside of the class FruitImpl. 唯一的区别是案例类FruitName是在FruitImpl类之外定义的。 Why does one version of the code fails and the other doesn't? 为什么一个版本的代码失败而另一个版本没有失败? What should one do to fix the error in the first example? 在第一个示例中,应该怎么做才能解决错误?

Without looking at the ScalaMock code, I'd say that the mock is not a true derivation of FruitImpl in the OO sense. 如果不看ScalaMock代码,我会说该模拟并不是OO意义上的FruitImpl的真实派生。 Its purpose is to allow method interception, so it only deals with the facade . 其目的是允许方法拦截,因此仅处理Facade It follows then that the mock actually has no definition of the path dependent type FruitName , and so cannot work with a method signature that depends on it. 随之而来的是,该模拟实际上没有定义与路径相关的类型FruitName ,因此无法使用依赖于该方法的方法签名。

This is precisely why it does work when the FruitName definition is moved out of FruitImpl . 这就是为什么当FruitName定义从FruitImpl移出时它确实起作用的FruitImpl It now exists independently of the mock, who's method signatures depending on it then work as expected. 现在,它独立于模拟程序而存在,模拟程序依赖于该模拟程序,然后按预期工作。

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

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