Tuesday, February 11, 2020

Spock: Expect two calls from one method with specific results.

This is probably nothing new to many people, but it was a very pleasant surprise to me, so I'm posting here in case there are others as clueless as I. 

Here's the situation. I've got a method under test, in Spock. (Yay! Groovy!) There is a mocked class that has a method that will be called twice, so we want to expect that, and we need to specify the return results because they are used by the method under test. In some scenarios, the expected params are known and easy to construct in the test, like a String literal. This is the easy one.

However, in some scenarios, the expected params are more difficult to construct in the test code, and I still want to expect the two calls in a specific order and with specific return values—which, again, are used downstream.

This is where I was stumped.  My very limited Spock skills came back to haunt me, and Google failed to hide my ignorance. No worries: I'm working on a project with the brilliant (and helpful) developers from Object Partners, and Neal Buesing came up with this little gem.

Needless to say, it worked like a charm, and kept me from cluttering up the test with a ton of code to construct the complex objects that would have been needed.

So, if you're reading and didn't know about this trick, tuck it away for later, and you won't have to admit to the world that you were stumped.

No comments: