Mock objects – A nice analogy
Recently I met an agile enthusiast from France. He is currently mentoring his team in India on agile. During our discussion about agile awareness in India, he was sharing his experience mentoring the folks out there.
What are mock objects?
Ans: Assume you are the owner of a pub and you do not want to let people with a pony tail into your pub. This is your business requirement. So you hire two bouncers. Ask to stand near the entrance and not let any one in who has a pony tail. You put them at work and go back home happily.
Suddenly a thought arises in your mind, what is the guarantee that these bouncers are doing their job? How can you be sure that they are not letting people with a pony tail into your pub?
So you call up your friend, who has a pony tail and tell him that you have free passes to your pub and you would like him to visit your pub. You also tell him if he has any issues getting in, please do call me up. Your friend with the pony tail goes to your pub, but the bouncers do not allow him. Yahoo! The bouncers are doing their job.
Now you get another doubt, what if the bouncers are not allowing any one in?
So you call up your friend, who does not have a pony tail and tell him that you have free passes to your pub and you would like him to visit your pub. You also tell him if he has any issues getting in, please do call me up. Your friend without the pony tail goes to your pub and the bouncers do allow him. Yahoo! The bouncers are doing their job.
Business requirement: To not allow people with pony tail into your pub.
Implementation: You hire bouncers to check for people with pony tail and not let them in.
So basically the bouncer class would call a method on the people class to check if they have a pony tail or not. If yes, then they do not allow them in else let them in.
In a test-first development environment it might so happy that you don‘t have the people class yet. You just want to test the bouncer class. Also you want to know if your logic in the bouncer class calls a method on the people class and checks for the pony tail rather than making its own assumptions. What do you do in such a situation?
You use mock objects. So you mock out the people class and also put a check in the mock object that the hasPonyTail method is called once.
QED – Quite easily done!