According to Wikipedia a Mock Object is defined as:
In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to test the behavior of a car during an accident.
So a Mock object is in essence a replacement for a real world object or process. A Mock object has the same interface as the real objects they are standing in for. But these Mock objects typically simulate the actual operations of the real world objects. This means that instead of calling an expensive, in terms of time and complexity, object like a web service, they can simulate the call and respond in realistic ways without the overhead of database interaction or network latency.
This allows the unit tests being written against the Mock to focus on the actual behavior but without the penalty of the real overhead. In a fairly complex application with potentially hundreds of unit tests, speed of test execution becomes a real issue. Mocks help keep that interaction realistic but not punitive.
Eventually in the testing of a system, the Mocks will need to be replaced by their real world counterparts, this is typically done in the integration or system testing phases of the project.
Mocks are different than Fakes. A Fake is simply an object that implements the interface of the object it replaces, usually with predetermined responses to each method call. A Mock goes further in that it is often coded to contain it's own assertions, and track state perhaps as well. In this way a Mock can determine and respond appropriately if its methods are called out of order, or prior to some initialization call etc.
A stub is typically even simpler than a Fake. A typical stub for example, could be a boolean function call, that is replaced with a simple "Return True" line of code. The functions parameters are not examined or validated, every call to the stub simply returns "True".
Among many other reasons to use Mocks, one reason comes to my mind from recent experience. We were testing a system that was time of day sensitive. Meaning that we needed to know during testing that several different portions of the system responded appropriately when the time of day was between certain time periods. With Mocks it was easy to provide this kind of functionality whereas with the real objects we would have had to reset clocks on 3 different systems, over and over, in order to achieve repeatable results.
Next post: Virtual Mocks
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Robert B. Porter - Powered by: newtelligence dasBlog 2.1.8102.813