[英]Idiomatically return None if Option contains None or contains unwanted type
[英]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.