Have you ever watched a movie where the main character is involved in some crazy action scene, like getting thrown through a glass window or rolling over a car? The actor playing the main character is not actually doing that stuff. It is a stunt double made to look like the actor and is specialized in doing the crazy stunts. What does this have to do with Unit Testing? Well, sometimes we work on a project with other people and the part we need to finish our portion of the program is not done yet, we need a stunt double. These stunt doubles we use in unit testing are fakes, mocks and stubs.
What’s the difference?
Fakes- A fake is an object that is has working implementations that are usually different from the production code. A fake would cut corners to get to the data and return it back to the class calling it. Using an in-memory database would be a good way to take advantage of fakes.
Mocks- Mocks are objects that register calls they receive. They are pre-programmed with specifications on what is supposed to happen when the method is called. Mocks are useful for when you need to test the behavior of a code rather than a result. For example, if you are testing an instant messaging application on the iPad you don’t want to have to send out a message for every single test you run. Instead you would create a mock object that verifies that the program instructed the message to send. This is testing the behavior of the program.
Stubs- A stub holds predefined data and returns it when called. We use stubs when we don’t want to touch the real data. or can’t. You create stubs and have them return a value that isn’t going to change, so you know exactly what the resultss should be when testing. For example, in class we talked a lot about classes named “Student”, “Grade”, and “Transcript”. We acted as though the transcript class was being written by a classmate and we were required to write tests for the Student and Grade classes without the real Transcript class. We were able to do this by creating a stub transcript class that return the information that we would expect in our tests. This is a way of checking that the method is still being called and that it works the way we want it to.
You can read more about this here:
http://www.softwaretestingmagazine.com/knowledge/unit-testing-fakes-mocks-and-stubs/
From the blog CS@Worcester – Rookey Mistake by Shane Rookey and used with permission of the author. All other rights reserved by the author.