pointyhat
pointyhat

Reputation: 596

spock mocks: capture arg and stub return value - can be separate?

I have a test that calls for:

  1. verifying interaction (method was called, and with the right args)
  2. the mock needs to return some benign return value, so as not to trigger any side effects.

The attached code does that, but I am wondering if there's a more readable way of doing it. Particularly, I think it would be good to separate the mocking bits (#1) from the stubbing bits (#2).

Any suggestions?

Thanks!

def "foo"() {
    setup:
    Payload payload
    Collaborator mock = Mock()
    underTest.collaborator = mock

    when: "doing something"
    underTest.doSomething()

    then: "collaborator's func is called once"
    1 * mock.func(*_) >>  { args ->
        payload = args[0] // 1. capture arg for inspection
        SOME_RETURN_VAL // 2. return a canned response
    }
    and: "collaborator is passed correct args"
    with(payload) {
        //...do some verification over payload
    }
}

Upvotes: 0

Views: 877

Answers (1)

kriegaex
kriegaex

Reputation: 67317

Let us consult the Spock documentation, shall we?

Combining Mocking and Stubbing

Mocking and stubbing go hand-in-hand:

1 * subscriber.receive("message1") >> "ok"
1 * subscriber.receive("message2") >> "fail"

When mocking and stubbing the same method call, they have to happen in the same interaction. In particular, the following Mockito-style splitting of stubbing and mocking into two separate statements will not work:

given:
subscriber.receive("message1") >> "ok"

when:
publisher.send("message1")

then:
1 * subscriber.receive("message1")

As explained in "Where to Declare Interactions", the receive call will first get matched against the interaction in the then: block. Since that interaction doesn’t specify a response, the default value for the method’s return type (null in this case) will be returned. (This is just another facet of Spock’s lenient approach to mocking.). Hence, the interaction in the given: block will never get a chance to match.

NOTE

Mocking and stubbing of the same method call has to happen in the same interaction.

Upvotes: 1

Related Questions