首页 > 解决方案 > Mockito:预期 0 个匹配器,1 个记录

问题描述

我有以下 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非常有效。

标签: scalaplayframeworkmockitoscalatestmockito-scala

解决方案


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

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

如果你添加猫集成它可以减少到只是

mockServiceB.execute(*) returnsF resultB

更多信息在这里


推荐阅读