使用Mockito + specs2模拟返回类型的默认值 [英] Mocking default values for return types with mockito + specs2
问题描述
给出一个模拟:
val myMock = mock[SomeClass]
我正在尝试进行设置,以使模拟返回各种类型的默认值.例如.对于返回String
的东西,它将返回""
.
I am trying to set it up so that the mock returns default values for various types. E.g. for things that returns String
, it would return ""
.
我发现了 RETURNS_SMART_NULLS
看起来像适用于基本返回类型(如String).这是我在Scala/Specs2中使用它的方式:
I discovered RETURNS_SMART_NULLS
which looks like it works for basic return types like String. Here is how I am using it in Scala / Specs2:
val myMock = mock[SomeClass].settings(smart = true)
现在是问题所在:由于我使用的是Scala,因此我的代码/API不会返回空值,而是返回Option值.所以我想做的是使模拟默认返回Option返回类型的非null值:None
(首选)或Some[T]
,其中T是容器中的类型(如果为String,则为Some("")
).
Now to the problem: since I am using Scala, my code / APIs do not return nulls but return Option values. So what I am trying to do is get the mock to default to returning a non null value for Option return types: either None
(preferred), or Some[T]
where T is the type in the container (if its String, then Some("")
).
因此,例如,如果SomeClass
具有类型为Option[String]
的属性address
,那么当调用myMock.address
而不是null时,我该如何配置Mockito以返回None
.这些null会导致下游错误.
So for example if SomeClass
has an attribute address
of type Option[String]
, how can I configure mockito to return None
when myMock.address
invoked instead of null. These nulls are causing downstream errors.
请注意,它对我来说不是一个可行的解决方案,可以专门模拟这些单独调用的每个行为(例如:myMock.address returns None
)
Note, its not a viable solution for me to specifically mock the behavior of each of these individual invocations (e.g: myMock.address returns None
)
推荐答案
我能够测试此类:
class Timers(i: Int, s: String) {
def returnOption: Option[Int] = Some(i)
def returnString: String = s
}
通过此测试:
import org.specs2.mutable.Specification
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.mockito.Mockito._
import org.mockito.stubbing.Answer
import org.mockito.invocation.InvocationOnMock
@RunWith(classOf[JUnitRunner])
class TimersSpec extends Specification {
val m = mock(classOf[Timers], new Answer[Any]() {
def answer(inv: InvocationOnMock) = {
inv.getMethod.getReturnType match {
case c if c == classOf[Option[_]] => None
case c if c == classOf[String] => ""
case _ => null
}
}
})
"A mock timer" should {
"return a None" in {
m.returnOption must beNone
}
"return a empty string" in {
m.returnString mustEqual ""
}
}
}
这篇关于使用Mockito + specs2模拟返回类型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!