Tuesday, 18 October 2011

What is Mock Objects?

Mock objects are objects that are isolated from there dependencies for testing purpose. In other words mock object is a simulated object that mimics the behavior of a real object in controlled ways. Mock objects are often used in unit testing to analyze the performance of actual objects. In this context, an object is the smallest testable part of an application. A mock object makes use of the same interface as the element of code it is intended to imitate.
Mock objects have two roles during a test case: actor and critic.
The actor behavior is to simulate objects that are difficult to set up or time consuming to set up for a test i.e.  database connection. Setting up a test database at the start of each test would slow testing to a crawl and would require the installation of the database engine and test data on the test machine. If we can simulate the connection and return data of our choosing we not only win on the pragmatics of testing, but can also feed our code spurious data to see how it responds. We can simulate databases being down or other extremes without having to create a broken database for real. In other words, we get greater control of the test environment.
If mock objects only behaved as actors they would simply be known as "server stubs". This was originally a pattern named by Robert Binder (Testing object-oriented systems: models, patterns, and tools, Addison-Wesley) in 1999.
A server stub is a simulation of an object or component. It should exactly replace a component in a system for test or prototyping purposes, but remain lightweight. This allows tests to run more quickly, or if the simulated class has not been written, to run at all.
However, the mock objects not only play a part (by supplying chosen return values on demand) they are also sensitive to the messages sent to them (via expectations). By setting expected parameters for a method call they act as a guard that the calls upon them are made correctly. If expectations are not met they save us the effort of writing a failed test assertion by performing that duty on our behalf.
In the case of an imaginary database connection they can test that the query, say SQL, was correctly formed by the object that is using the connection. Set them up with fairly tight expectations and you will hardly need manual assertions at all.

A mock object can be useful in place of a real object that:
  • Runs slowly or inefficiently in practical situations
  • Occurs rarely and is difficult to produce artificially
  • Produces non-deterministic results
  • Does not yet exist in a practical sense
  • Is intended mainly or exclusively for conducting tests

No comments:

Post a Comment