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

时间:2016-03-08 22:05:50

标签: mocking spock

我需要测试一些与eventbus的交互。我已经在Event类中包装了所有参数。问题是,当我想验证事件时,我必须在我的测试中创建事件对象并提供所有参数。我更愿意只指定重要的参数来明确哪些参数很重要。

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 * _
}

1 个答案:

答案 0 :(得分:2)

您可以使用闭包指定参数。如果闭包返回true或者不抛出异常,则将匹配交互。

例如:

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