在命名函数中换行argThat



假设我有这样的东西(非常过度实现(:

case class Foo(bar: String)
val mockFnThatTakesFoo = mock[Foo => Unit]
def fooHasBarSetTo(expectedBar: String, foo: Foo): Boolean = {
val actualBar = foo.bar
actualBar shouldEqual expectedBar
true
}
mockFnThatTakesFoo(argThat(fooHasBarSetTo("blah", _))) wasCalled once

这是有效的。然而,断言本身有点复杂,可以使其更具可读性
我试过这个:

val withFooHavingBarSetTo = (expectedBar: String) => argThat(fooHasBarSetTo(expectedBar, _))
//and then
mockFnThatTakesFoo(withFooHavingBarSetTo("blah")) wasCalled once

整洁多了!但不起作用:/

> [info] FooSpec:
[info] - should do stuff *** FAILED ***
[info]   org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
[info] 1 matchers expected, 2 recorded:
[info] -> at com.foo.FooSpec.argThat(FooSpec.scala:28)
[info] -> at com.foo.FooSpec.$anonfun$new$5(FooSpec.scala:204)

知道怎么做吗?

我相信Mockito是使用宏实现的,它跟踪argThat和其他Mockito方法的放置位置。例如,如果你试图创建一个像这样的变量

val blahBar = argThat(fooHasBarSetTo("blah", _))

您将得到一个异常";这里检测到的错误放置或误用的参数匹配器";。因此,不可能从另一个方法返回argThat-matcher。

如果您需要重用具有不同参数值的模拟匹配器,我只看到一种可能的解决方案,如

def mockCalledOnceWithFooHavingBar(expectedBar: String) {
mockFnThatTakesFoo(argThat(fooHasBarSetTo(expectedBar, _))) wasCalled once
}
mockCalledOnceWithFooHavingBar("blah")
mockCalledOnceWithFooHavingBar("bar")

相关内容

  • 没有找到相关文章

最新更新