Reputation: 596
I have a test that calls for:
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
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 thethen:
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 thegiven:
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