Mocking and faking are ways to isolate code or components to ensure that unit tests run against the testable unit of code only without actually utilizing other components or dependencies of an application. Mocking differs from faking in that a mock can be inspected to assert the results of a test.
Mocking and faking are ways to isolate code or components to ensure that unit-tests run against the testable unit of code only without actually utilizing other components or dependencies of an application. Mocking differs from faking in that a mock can be inspected to assert the results of a test.
Reasons for use
In a unit test, mock objects can simulate the behavior of complex, real objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test. If an actual object has any of the following characteristics, it may be useful to use a mock object in its place:
- The object supplies non-deterministic results (e.g., the current time or the current temperature);
- It has states that are difficult to create or reproduce (e.g., a network error);
- It is slow (e.g., a complete database, which would have to be initialized before the test);
- It does not yet exist or may change behavior;
- It would have to include information and methods exclusively for testing purposes (and not for its actual task).
For example, an alarm clock program which causes a bell to ring at a certain time might get the current time from the outside world. To test this, the test must wait until the alarm time to know whether it has rung the bell correctly. If a mock object is used in place of the real object, it can be programmed to provide the bell-ringing time (whether it is actually that time or not) so that the alarm clock program can be tested in isolation.
Most commonly, isolation frameworks are used to dynamically build a mock, such as: