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 report. This operation can last minutes, hours, or, in some cases, even days.

The preceding reasons in the support of mock objects apply to any type of testing. However, in the case of unit tests and, especially, in the context of TDD, there is one more reason, perhaps more important than others. Mocking allows us to isolate all dependencies used by the method we are currently working on. This empowers us to concentrate on a single unit and ignore the inner workings of the code that the unit invokes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.188.238