1

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.

Anand Patel
  • 6,031
  • 11
  • 48
  • 67
  • I think the terms "mock-objects" and "stubs" are rather subjective and ambigious. Could you tell me what you think the difference is between the two? :) – cwap Aug 13 '09 at 12:15
  • Wikipedia: "Method stub, in computer programming, a piece of code used to stand in for some other programming functionality" // "Mock object, simulated objects that mimics the behavior of real objects in controlled ways" :) – cwap Aug 13 '09 at 12:17
  • 1
    @Meeh - Search for Martin Fowler's read-worthy "mocks aren't stubs" article – Gishu Aug 13 '09 at 12:28

3 Answers3

4

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.

Community
  • 1
  • 1
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
2

Martin Fowler describes the differences very well on his bliki

AutomatedTester
  • 22,188
  • 7
  • 49
  • 62
1

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
  • 134,492
  • 47
  • 225
  • 308
  • That is to the point explanation. Thanks for answering the question. Do you recommend any blog or articles for the same. – Anand Patel Aug 13 '09 at 12:26
  • 1
    The post linked to by AutomatedTester below is one you could start with. Understand the diff between state-based and interaction-based testing. – Gishu Aug 13 '09 at 12:32