A mock object is generally used as a
stand-in, or replacement, for a real object while the system is being unit
tested. The main purpose of using a mock object is to allow our tests to
be more focused, self contained, predictable and reliable. By having our
unit tests more isolated and predictable we can identify the cause of the
failure in less time and false negatives (tests which fail but should
pass) are reduced.
An example of when a mock object might be used is when
a feature in your system is required to return different results based on
the current time of day. Given this requirement, how could it be tested? It
would have a number of problems, for example you would have to have
different test logic depending on the time of day the tests where executed and
worse, only being able to execute the test at certain times of the day in order
for it to execute the conditional logic being tested. Identifying the real
reason why a test has failed would also become a problem as it could be
because of the code or because of the time the test was executed.
This is where mock objects become useful. A mock object
would allow us to replace the unpredictable functionality of obtaining the
time, and replace it with pre-setup logic with known values which we could test
against. We could then write and configure different tests to take into account
the different requirements without having to worry about when or where the
tests are actually executed. This makes the tests more useful as they
could be run and instantly report back if there was a problem. As a
result, tests can be run more often and problems are likely to be fixed in a
much shorter time as one of the external dependencies which had the potential
to cause problems has been removed.
Other reasons why you might want to use mock objects in your
unit tests include:
·
Access to the real object is slow because of database calls or
long calculations.
·
The real object uses a call back.
·
The real object requires access to external resources which
are unavailable.
·
The real object has not finished being developed.