Spock Mock 方法将对象与占位符匹配

Spock Mock method matching objects with placeholders

我需要测试一些与事件总线的交互。我已将所有参数包装在事件 类 中。问题是,当我想验证事件时,我必须在测试中创建事件对象并提供所有参数。我宁愿只指定重要的参数,以明确哪些参数是重要的。

def "initial layout should call page events"() {
    given: "register for event"
    def listener = Mock(Closure)
    eventBus.registerForEvent(PageVisibilityChangedEvent, listener)
    when: "viewport twice the size of our pages and can fit 2 pages"
    worldport.updateScreenSize(new IntSizeImpl(200, 400))
    then: "after the initial layout pages 0 and 1 should have become visible"
    1 * listener.call(new PageVisibilityChangedEvent(_, 0, _, Visibility.VISIBLE, _))
    1 * listener.call(new PageVisibilityChangedEvent(_, 1, _, Visibility.VISIBLE, _))
    0 * _
}

您可以指定带有闭包的参数。如果闭包 return 为真或不抛出异常,则交互将被匹配。

例如:

1 * listener.call({ it.visibility == VISIBLE && it.p in [0, 1] })