Follow @RoyOsherove on Twitter

The Mock Objects elevator speech

A friend asked me by email the other day :"So why do I need mock objects?" I came up with this in roughly 3 minutes so it's a bit rough, but it'll do to drive the point home, I hope. Note, that this does not really explain the *technical* side of it too much. Just the logic behind the concept.
 
Mock objects are there for when you need to replace or remove dependencies from code under test.
Let's say you have a class that manages user logins. Whenever a user login fails the class needs to report to a logger class, or maybe even an email class, or some remote web service to authenticate. If you want to write a test for the logic in the login class (an tests are just methods that call methods on the tested class, really) you want your test to run fast, and to run easily without too much fussing and configuration so that you can get fast feedback.
Also - if you replace that emailer class or authentication service class with a "fake" one you can mimic various scenarios of failures which are hard to recreate in real life or would take LOT of code. An example would be "Authentication fails/succeeds for user name". Without faking it, you'd need a lot of configuration to test that you class indeed handless success of login failure correctly each time. 
Mocks are spies in disguise for you tests - double agents. they let you do what you want without your real code knowing about it, and tell you everything that happened to them like "your class *should* have called my 'authenticate' method with param x and Y but it actually called it with the wrong value.. Your test should *fail*".
 

Nice PDC Contest Entry from Steve Hebert

Who's reading me?