Mock Object - Reasons For Use

Reasons For Use

In a unit test, mock objects can simulate the behavior of complex, real (non-mock) objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test. If an object has any of the following characteristics, it may be useful to use a mock object in its place:

  • supplies non-deterministic results (e.g., the current time or the current temperature);
  • has states that are difficult to create or reproduce (e.g., a network error);
  • is slow (e.g., a complete database, which would have to be initialized before the test);
  • does not yet exist or may change behavior;
  • 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.

Read more about this topic:  Mock Object

Famous quotes containing the words reasons for and/or reasons:

    Write to the point: say immediately what you want to say most, even if it doesn’t “come first.” There are three reasons for doing this. First, you will then have said it, even if nothing else gets said. Second, your readers will then have read it, even if they read no more. Third, having said it, you are likely to have to say something more, because you will have to explain and justify what you chose to say.
    Bill Stott (b. 1940)

    I call it our collective inheritance of isolation. We inherit isolation in the bones of our lives. It is passed on to us as sure as the shape of our noses and the length of our legs. When we are young, we are taught to keep to ourselves for reasons we may not yet understand. As we grow up we become the “men who never cry” and the “women who never complain.” We become another generation of people expected not to bother others with our problems.
    Paula C. Lowe (20th century)