Chapter 6. Mock Objects
Introduction
Writing tests for simple, standalone Java classes is easy. Just create an instance of your class and run tests against its methods. But testing gets a whole lot more interesting for classes with complex dependencies on other parts of your application. When testing becomes difficult, consider refactoring your code in order to minimize dependencies. But there will always be cases where classes cannot be tested in isolation.
Suppose that a class named Automobile
only runs in
the context of a class named Engine
. In order to
test all aspects of the Automobile
class, you find
that you have to create many different kinds of
Engine
s. Rather than create real
Engine
objects, which may require a lot of setup
logic, you can write a dummy Engine
implementation. This dummy implementation is known as a mock object
and it provides a simple way to set up fake testing data.
The mock Engine
can even include assertions to
ensure that instances of Automobile
use the
Engine
correctly. For example, the
Engine
may verify that
Automobile
only calls the Engine.startup( )
method one time. This ability to verify that objects use
their environment correctly is a key advantage of mock objects when
compared to other testing techniques that only check to see if
classes react to method calls correctly.
A mock object is a “fake” implementation of a class or interface, almost always written for the specific purpose of supporting unit tests. When writing JDBC unit tests, you might ...
Get Java Extreme Programming Cookbook 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.