hen you're unit testing, you often want to test an individual unit of code without testing its dependencies. One common solution to this problem is to utilize the mock-object testing pattern. Though the mock-objects pattern can lead to a great working solution, many times, it is simply overkill. Extreme Programming (XP) espouses the principle: do the simplest thing that could possibly work. To this end, mock objects aren't always the simplest thing possible. This article introduces you to an approach for testing with stubs using a pattern called "pseudo objects."
| Author's Note: The examples in this article are provided in Java, but the patterns that are discussed are language agnostic. You can use these patterns while programming in any object-oriented language.
Testing Strategies, Mocks, and Stubs
In interaction-based unit testing, tests typically pass mock objects into methods so that the mock objects can verify the implementation of the code that is being tested. Mocks are fake objects that record the manner upon which they are operated and can verify whether they were operated on properly.
In state-based unit testing, real system objects are passed to the method that is being tested and the output of the method is asserted, but the implementation of the method is not tested. If a real system object is difficult to create within the context of the test, stubs are usually used instead. Stubs, like mock objects, are fake objects as well, but they usually have no logic or recording capability. Stubs just return canned data.
| Author's Note: For a more in-depth discussion of the difference between mock objects (also called mocks) and stubs, as well as the differences between interaction and state-based unit testing, see Martin Fowler's recent paper "Mocks Aren't Stubs."
The main argument for choosing state-based unit testing over interaction-based unit testing is that interaction-based unit testing couples the tests to the implementation. I'll show you some examples of interaction-based unit testing using mocks, then I'll introduce you to state-based unit testing by showing you a simple pattern that will allow you to easily create stubs.