Chapter 7. Testing with mock objects

 

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.

Rich Cook

This chapter covers

  • Introducing and demonstrating mock objects
  • Performing different refactorings
  • Practicing on the HTTP connection sample application
  • Introducing the EasyMock and the JMock libraries

Unit testing each method in isolation from the other methods or the environment is certainly a nice goal. How do you perform this feat? You saw in chapter 6 how the stubbing technique lets you unit test portions of code by isolating them from the environment (for example, by stubbing a web server, the file system, a database, and so on). What about fine-grained isolation, like being able to isolate a method call to another class? Is that possible? Can you achieve this without deploying huge amounts of energy that would negate the benefits of having tests?

Yes! It’s possible. The technique is called mock objects. Tim Mackinnon, Steve Freeman, and Philip Craig first presented the mock objects concept at XP2000. The mock objects strategy allows you to unit test at the finest-possible level and develop method by method, while providing you with unit tests for each method.

7.1. Introducing mock objects

7.2. Unit testing with mock objects

7.3. Refactoring with mock objects

7.4. Mocking an HTTP connection

7.5. Using mocks as Trojan horses

7.6. Introducing mock frameworks

7.7. Summary