As I was doing some at home research on stubs and mocking for one of my courses, I came across the idea of spies. Unlike stubs and mocks which allow for the program and tests to run while giving canned answers or being unfinished, spies perform a much needed but previously unfilled role.
Spies are used to ensure a function was called. It’s of course more in-depth than this but that’s it’s basic function.
On a deeper level a spy can not only tell if a call to function was made, but how many calls, what arguments were passed, and if a specific argument was passed to the function.
Abby Campbell has great examples of these in her blog, “Spies, Stubs, and Mocks: An Introduction to Testing Strategies” where she displays easy to understand code. I would definitely recommend taking a look at them, her blog also goes in depth on stubs and mocking.
When writing test cases, the addition of a spy to ensure a thorough case can’t be undersold. Imagine a simple test case that uses a stub, without the use of a spy you can’t be sure the correct function was called unless every function returns a different value which would be inefficient to set-up. By using a spy the function called is checked, the argument passed is checked, and the output can even be checked as well leaving little to no room for an error in the test case aside from human error.
With the addition of spies to our arsenal of tools for software testing we check off the need to find a reliable way of testing for ensuring correct function calls and arguments. I plan on carrying this new tool with me throughout the rest of my career. It allows for much more efficient, effective, and sound testing.
From the blog CS@Worcester – DPCS Blog by Daniel Parker and used with permission of the author. All other rights reserved by the author.