【问题标题】:Matching any parameterless function as an argument in scala Mockito将任何无参数函数匹配为scala Mockito中的参数
【发布时间】:2012-09-23 11:52:05
【问题描述】:

我正在尝试验证是否使用 Mockito 调用了以下方法:

class Notifier {
  def forward(request: ServletRequest)(onFailure: => Unit) : Unit
}

这是对模拟的验证:

val notifier = mock[Notifier]
there was one(notifier).forward(any[ServletRequest])(any[() => Unit])

我得到了例外:

   The mock was not called as expected: 
    Invalid use of argument matchers!
    3 matchers expected, 2 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"));

我知道这是由最后一个无参数函数引起的。如何在此处正确执行验证?

【问题讨论】:

  • => Unit 不是函数类型,而是按名称参数。
  • @BenJames 那么(onFailure: Unit) 与(onFailure: => Unit) 有何不同?
  • 区别在于代码块的执行时间。有一个参数 forward(onFailure: Unit) 没有意义。该参数将在调用 forward 之前进行评估。使用 forward(onFailure: => Unit) 方法 forward 决定何时评估参数。
  • 方法定义和期望不匹配。方法转发需要一个名称参数,期望参数是一个零参数的函数。

标签: scala mocking mockito specs


【解决方案1】:

你可以试试Function0[Unit] 吗?

there was one(notifier).forward(any[ServletRequest])(any[Function0[Unit]])

【讨论】:

    猜你喜欢
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2020-09-12
    • 2013-05-03
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多