Mockito:预期有 0​​ 个匹配器,记录有 1 个

Mockito: 0 matchers expected, 1 recorded

我有以下 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
   }
} 

ServiveAServiceB的定义是

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(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

您需要这样做:

进口org.mockito.ArgumentMatchersSugar._

when(mockServiceB.execute(any[ClassA], eqTo(Some(3)))).thenReturn(Future{resultB})

当您使用 any 并且该函数接收到多个参数时,您需要使用 eq(something) 传递其他不是 any 的参数,希望这对您有所帮助。

已编辑:我的错误忘记了导入并且是 eqTo 而不是 eq

使用 mockito-scala 的惯用语法,所有与默认参数相关的东西都将由框架处理

mockServiceB.execute(*) returns Future.sucessful(resultB)

如果您添加猫集成,它可能会减少到

mockServiceB.execute(*) returnsF resultB

更多信息here