我拥有以下PlaySpec:
"Service A" must {
"do the following" in {
val mockServiceA = mock[ServiceA]
val mockServiceB = mock[ServiceB]
when(mockServiceA.applyRewrite(any[ClassA])).thenReturn(resultA) // case A
when(mockServiceB.execute(any[ClassA])).thenReturn(Future{resultB})
// test code continuation
}
}
ServiveA
和ServiceB
的定义是
class ServiceA {
def applyRewrite(instance: ClassA):ClassA = ???
}
class ServiceB {
def execute(instance: ClassA, limit: Option[Int] = Some(3)) = ???
}
模拟ServiceA#applyRewrite
效果很好。
模拟ServiceB#execute
失败,但出现以下异常:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at RandomServiceSpec.$anonfun$new$12(RandomServiceSpec.scala:146)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
尽管异常中包含的说明对我来说有点违反直觉,但我尝试了以下操作:
when(mockServiceB.execute(anyObject[ClassA])).thenReturn(Future{resultB})
when(mockServiceB.execute(anyObject())).thenReturn(Future{resultB})
when(mockServiceB.execute(anyObject)).thenReturn(Future{resultB})
when(mockServiceB.execute(any)).thenReturn(Future{resultB})
when(mockServiceB.execute(any, Some(3))).thenReturn(Future{resultB})
when(mockServiceB.execute(any[ClassA], Some(3))).thenReturn(Future{resultB})
很遗憾,所有步骤均无济于事。唯一改变的是异常引用的预期和记录的匹配器的数量。
对我来说最奇怪的是,该模拟对于案例A 非常适用。
答案 0 :(得分:3)
使用micito-scala的惯用语法,所有与默认参数相关的内容都将由框架处理
mockServiceB.execute(*) returns Future.sucessful(resultB)
如果添加cats集成,则可能会减少到
mockServiceB.execute(*) returnsF resultB
更多信息here
答案 1 :(得分:1)
您需要执行以下操作:
导入org.mockito.ArgumentMatchersSugar ._
when(mockServiceB.execute(any[ClassA], eqTo(Some(3)))).thenReturn(Future{resultB})
当您使用any且函数接收多个参数时,您需要使用eq(something)传递不存在的其他参数,希望对您有所帮助。
编辑:我很遗憾忘记了导入,它是eqTo而不是eq