8 Testing with mock objects

 

This chapter covers

  • Introducing and demonstrating mock objects
  • Executing different refactorings with the help of mock objects
  • Practicing on an HTTP connection sample application
  • Working with and comparing the EasyMock, JMock, and Mockito frameworks

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

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

The answer is yes. The technique is called mock objects. Tim Mackinnon, Steve Freeman, and Philip Craig first presented the mock-objects concept at XP2000. The strategy allows you to unit test at the finest possible level. You develop method by method after having provided unit tests for each method.

8.1 Introducing mock objects

8.2 Unit testing with mock objects

8.3 Refactoring with mock objects

8.3.1 Refactoring example

8.3.2 Refactoring considerations

8.4 Mocking an HTTP connection

8.4.1 Defining the mock objects

8.4.2 Testing a sample method

8.4.3 Try #1: Easy refactoring technique

8.4.4 Try #2: Refactoring by using a class factory

8.5 Using mocks as Trojan horses

8.6 Introducing mock frameworks

8.6.1 Using EasyMock

8.6.2 Using JMock

8.6.3 Using Mockito

Summary

sitemap