Search code examples
javaunit-testingtestingspock

Using runtime variables in spock verification


I am trying to write a simple test where I would like to verify mock call with some runtime variable. At the moment it looks like this:

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)
    }

}

But what I want to achieve is also to verify if the payload of the event was correct - which means that the event contains the id, something like this:

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

Is it somehow possible to achieve such verification in Spock?


Solution

  • You can capture the Event by stubbing the push() method on the 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
    }