[英]How to mock function returning AnyVal with Mockito in Scala / Specs2?
I would like to stub a function returning AnyVal using Mockito in Scala (Specs2 to be precise), but it doesn't seam to work: 我想在Scala中使用Mockito(确切地说是Specs2)来存储返回AnyVal的函数,但是它不会工作:
import org.specs2.mutable._
import org.specs2.mock._
case class V(s: String) extends AnyVal
class A {
def f: V = new V("Hello")
}
class Sample extends Specification with Mockito {
"Mockito" should {
"mock A" in {
val a = mock[A]
a.f returns new V("hoge")
a.f match {
case V("hoge") => success
case _ => failure
}
}
}
}
This fails with: 这失败了:
V cannot be returned by f()
f() should return String
I found kind of workaround (based on which I provided above snippet) using marker interface/trait: https://gist.github.com/mtgto/9251779 我使用标记接口/特征找到了一种解决方法(基于我在上面提供的代码片段): https : //gist.github.com/mtgto/9251779
but this is not any solution for me, hence it changes returned type (because of mocking/test library issue). 但这对我来说不是任何解决方案,因此它会更改返回类型(因为模拟/测试库问题)。
Anyone has seen this before and knows how to stub such function? 以前任何人都看过这个并且知道如何存根这样的功能?
I found one way of stubbing this function - using original Mockito's doReturn with underlying AnyVal's type (String in this case) instead of AnyVal itself, so: 我发现了一种简化此功能的方法 - 使用原始的Mockito的doReturn与底层AnyVal的类型(在本例中为String)而不是AnyVal本身,所以:
org.mockito.Mockito.doReturn("hoge").when(a).f
instead of: 代替:
a.f returns new V("hoge")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.