I started to play with Moq a few weeks back under the guise of Project NEric and then… real work got in the way. However I am today revisiting mocking as I am reviewing a potential article for the Flash on, let me think, mocking. The article touches on Mocking vs Stubs which is handy, as “back in the day” my team relied heavily on stubs (clever stubs at that) and I was confused about the differences between stubbing and mocking. I’m still not 100% there but I found the following useful.
Mocks and stubs pretend to be something else for the duration of a test.
And then goes on to a rather nice explanation of the difference:
Use mocks to test interaction with dependencies.
Use stubs to ignore dependencies.
Don’t use either if you don’t have to.
Or if you prefer:
Mocks replace existing methods and fail your test unless those methods are called.
Stubs simply replace methods.
Martin Fowler of ThoughtWorks has a whole piece on Mocks aren’t Subs. It is a medium read but in amongst it we have (paraphrased):
Test Double is the generic term for any kind of pretend object used in place of a real object for testing purposes. There are four kinds of double:
- Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
- Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production.
- Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
- Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
My confusion really stems from the fact that “back in the day” the team I worked with called all the four types of Test Double listed above … drum roll … stubs.