Search The Blog
About this site

@RoyOsherove

Subscribe!

This site aims to connect all the dots of my online activities - from tools, books blogs and twitter accounts, to upcoming conferences, engagements and user group talks.

from 5whys.com
Twitter: @RoyOsherove
My Book: The Art of Unit Testing
Latest Posts
« Nice PDC Contest Entry from Steve Hebert | Main | Who's reading me? »
Thursday
Jun302005

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*".
 

PrintView Printer Friendly Version

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>