Using stubs and mock objects

Mocks Aren't Stubs, by Martin Fowler, is an article describing the differences between stubs and mocks. A common characteristic for both is that dependencies that the test target depends are replaced with implementations that give feedback about execution, and may offer the possibility of altering the runtime environment from the test case. Fowler defines mock objects in the following manner:

"The term 'Mock Objects' has become a popular one to describe special case objects that mimic real objects for testing. Most language environments now have frameworks that make it easy to create mock objects. What's often not realized, however, is that mock objects are but one form of special case test object, one that enables a different style of testing."

The TestSource.cpp example code uses an implementation, which logs every method execution to a file with a macro _LOGF. The macro can be changed to write the result to a dynamic buffer. The test case can then execute the test and after execution verify from the buffer that certain methods are called (with the right content), and in the right order. This kind of passive implementation replacing is referred to as stubbing.

When the semantics of a stubbed method can be altered dynamically (from the test case), the implementation approach should be called mocking. When unit testing shall reach high coverage, it is practical to have mock implementations for each class. Because actual classes usually refer to each other, the test cases can select which instances to replace with a mock object, and where to use a concrete object.