views:

77

answers:

3

In my experience anything that can be achieved using mock objects, could be achieved using stubs. Are there any scenarios, where stubs cannot be used and mock objects serves well.

+4  A: 

Mocks usually include the ability to check whether the methods have been called, while stubs just return the stubbed data. See my question on the differences between faking, mocking, and stubbing for more info.

tvanfosson
+1  A: 

Martin Fowler describes the differences very well on his bliki

AutomatedTester
+1  A: 

Stubs are objects that stand-in/double for actual collaborators in your test and provide canned answers to certain requests. Stubs are usually hand-crafted to boot. This means you could end up maintaining (tedious?) a lot of fake objects if you follow this approach religiously.

Mocks on the other hand are generally dynamic - You don't maintain the source for these test doubles. Instead you use a mocking framework, which hands out a mock implementation of a particular interface at run-time. Mocks allow you to specify expectations (these methods should be called in this sequence, with these parameters and when they are, return these values) and verify that they were met at the end of the test.

short answer: Use stubs sparingly to overcome minor hurdles where you are not interested in the interaction with the collaborator but just want to get it out of the way of the test. Use Mocks for interaction based testing - where you are interested in how the SUT and the mocked collaborator interact.

Gishu
That is to the point explanation. Thanks for answering the question. Do you recommend any blog or articles for the same.
Anand Patel
The post linked to by AutomatedTester below is one you could start with. Understand the diff between state-based and interaction-based testing.
Gishu