To solve this problem, dependencies such as the DAO layer can be replaced by stand-ins
called mock objects. Instead of the real thing, we will create a mock replacement for the
AccountDao, which we will set into the AccountServiceImplobject before the test is run. This
way we will have full control over any dependencies, isolating the service object to be the
variable under test, as well as avoiding any interaction with external resources.
■NoteDependency Injection plays a big part in allowing for easy testing through mock objects. Because
the dependency is set into the class via a simple setter, the dependency can easily be substituted with a
mock object at test time.
Mock Objects
Mock objects add intelligence and programmability to stub classes, making them in essence
scriptable stubs. Think of mock objects as smart placeholders for dependencies. Mock objects
are created dynamically, inside the tests that utilize them. They typically are implemented
using JDK java.lang.reflect.Proxy objects, implementing the interface of the dependency
while replacing the behavior. More advanced mock object libraries also support creating
mocks for classes that do not implement interfaces.
Mock objects allow you to script the behavior of the mock in order to create different
situations for testing. For instance, you can control which objects are returned from a method
call, or you can instruct the mock object to throw an exception instead of returning a value.
This technique allows you to essentially inject objects into tests that are the results from
method calls.
Mock objects also let you specify exactly which methods should be called on the mock,
and in what order. This is a type of inside-outtesting, as you can ensure that only the expected
methods on a dependency are called. Once configured, you can instruct the mock object to
fail the test if an expected method was never called or if a method was called on the mock that
was never expected.
There are three main mock object libraries, each with their own pros and cons. Refer to
Table 10-1.
Table 10-1.Mock Object Libraries
Title URL Documentation Notes
MockObjects http://www.mockobjects.com Minimal, lacking. One of the first mock
object libraries.
jMock http://www.jmock.org Good, included Getting Rewrite of
Started Guide and MockObjects,
tutorials. handles mocking
interfaces and classes.
EasyMock http://www.easymock.org Good, many examples. Used by Spring for
testing.
292 CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS