MatcherException,尽管在测试[Scala]中使用了any()和eq()

MatcherException,尽管在测试[Scala]中使用了any()和eq(),scala,mockito,scalatest,Scala,Mockito,Scalatest,我有一个具有以下签名的方法: def fetchCode[T]( seconds: Int, client: String, scope: String, data: T, retryLimit: Int = 10 )(implicit formats: Formats): String 在我的测试中,我试图将其模拟为: val accessCode:

我有一个具有以下签名的方法:

def fetchCode[T](
      seconds:        Int,
      client:         String,
      scope:          String,
      data:           T,
      retryLimit:     Int = 10
  )(implicit formats: Formats): String
在我的测试中,我试图将其模拟为:

val accessCode:           String = "CODE"
when(
        mockService
          .fetchCode[String](
            any[Int],
            any[String],
            Matchers.eq(partner.name),
            any[String],
            any[Int]
          )
      ).thenReturn(accessCode)

verify(mockService).fetchCode(
        Matchers.any(),
        Matchers.any(),
        Matchers.eq(partner.name),
        Matchers.any(),
        Matchers.any()
      )
在运行此测试时,我仍然看到以下错误:

Invalid use of argument matchers!
6 matchers expected, 5 recorded:
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"));

For more info see javadoc for Matchers class.

我不明白为什么会出现这个错误-我只需要5个匹配器-每个参数一个,为什么需要6个?

隐式格式:格式也作为参数传递,所以mockito需要能够匹配它。

隐式格式:格式也作为参数传递,所以mockito需要能够匹配它。

正如@Levi在他的回答中提到的,为了使用mock,您需要处理该方法得到的所有参数。正如您在错误消息中看到的:

6 matchers expected, 5 recorded
您需要做的是在新的paranthesis中添加与原始方法完全相同的[Formats],并提供它们的模拟值:

when(
mockService
  .fetchCode[String](
    any[Int],
    any[String],
    Matchers.eq(partner.name),
    any[String],
    any[Int]
  )(any[Formats])
).thenReturn(accessCode)

verify(mockService).fetchCode(
Matchers.any(),
Matchers.any(),
Matchers.eq(partner.name),
Matchers.any(),
Matchers.any()
)(any[Formats])

正如@Levi在他的回答中提到的,为了使用mock,您需要处理该方法得到的所有参数。正如您在错误消息中看到的:

6 matchers expected, 5 recorded
您需要做的是在新的paranthesis中添加与原始方法完全相同的[Formats],并提供它们的模拟值:

when(
mockService
  .fetchCode[String](
    any[Int],
    any[String],
    Matchers.eq(partner.name),
    any[String],
    any[Int]
  )(any[Formats])
).thenReturn(accessCode)

verify(mockService).fetchCode(
Matchers.any(),
Matchers.any(),
Matchers.eq(partner.name),
Matchers.any(),
Matchers.any()
)(any[Formats])

这是令人惊讶的,我看到其他测试类似地模拟它,但没有模拟隐式参数!你知道如何模拟隐式参数吗?这很奇怪,我看到其他测试也在模拟它,但没有模拟隐式参数!你知道如何模仿隐式参数吗?我明白了!我不知道我们可以做任何[格式]-谢谢!我试过这个,效果很好!我懂了!我不知道我们可以做任何[格式]-谢谢!我试过这个,效果很好!