Why mocks?

The following list represents some of the reasons why we employ mock objects:

  • The object generates nondeterministic results. For example, java.util.Date() provides a different result every time we instantiate it. We cannot test that its result is as expected:
java.util.Date date = new java.util.Date(); 
date.getTime(); // What is the result this method returns?
  • The object does not yet exist. For example, we might create an interface and test against it. The object that implements that interface might not have been written at the time we test code that uses that interface.
  • The object is slow and requires time to process. The most common example would be databases. We might have a code that retrieves all records and generates a ...

Get Test-Driven Java Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.