【问题标题】:MatchersException despite using any() and eq() in Test [Scala]尽管在测试 [Scala] 中使用了 any() 和 eq(),但 MatchersException
【发布时间】:2021-03-16 00:40:18
【问题描述】:

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

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 个?

【问题讨论】:

    标签: scala mockito scalatest


    【解决方案1】:

    正如@Levi 在他的回答中提到的,您需要解决方法获取的所有参数,以便使用模拟。正如您所看到的错误消息的一部分:

    6 matchers expected, 5 recorded
    

    您需要做的是在新的括号中添加any[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])
    

    【讨论】:

    • 我明白了!我不知道我们可以做一个any[Formats] - 谢谢!我试过了,它有效!
    【解决方案2】:

    implicit formats: Formats 也作为参数传递,因此 mockito 需要能够匹配它。

    【讨论】:

    • 这令人惊讶,我看到其他测试类似地模拟它,但没有模拟隐式参数!
    • 你知道如何模拟隐式参数吗?
    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    相关资源
    最近更新 更多