首页 > 解决方案 > 在 spock 验证中使用运行时变量

问题描述

我正在尝试编写一个简单的测试,我想用一些运行时变量来验证模拟调用。目前它看起来像这样:

class Spec extends Specification implements SampleData {

    EventBus eventBus = Mock()

    Facade facade = new Configuration().facade(eventBus)

    def "when the method is called an proper event is emitted"() {
        when:
            def id = facade.call(sampleData)

        then:
            1 * eventBus.push(_ as Event)
    }

}

但我想要实现的也是验证事件的有效负载是否正确 - 这意味着事件包含id,如下所示:

then:
        1 * eventBus.push(new Event(id))

是否有可能在 Spock 中实现这样的验证?

标签: javaunit-testingtestingspock

解决方案


您可以Event通过push()EventBus.

def "when the method is called a proper event is emitted"() {
    given:
        EventBus eventBus = Mock()
        Facade facade = new Configuration().facade(eventBus)
        Event received
    when:
        def id = facade.call(sampleData)
    then:
        1 * eventBus.push(_ as Event) >> { Event event -> received = event }
        received.id == id
}

推荐阅读