We can recommend either jMock or EasyMock for your mock object needs. As noted,
Spring uses EasyMock for testing, so you may want to choose this package due to the number
of examples available in the Spring source code. However, we have the most experience with
jMock, so we will use it for the examples in this chapter.
With the mock object library chosen, it’s time to write the unit test for AccountServiceImpl.
Mock Object Techniques
We use mock objects during testing for two main reasons: to isolate the class under test from
outside influence and to control dependencies.
While unit tests should test a single unit of code in isolation, it’s rare to find a class or a
method that is completely void of dependencies in one form or another. If the dependency is
a simple POJO, using the newoperator is an easy way to create an instance used just for the
test. However, if the dependency is not easily created or requires heavyweight resources such
as database connections, using the newoperator isn’t often possible. Mock objects step in to
“mock” the dependency, thus allowing the code under test to operate without invoking out-
side resources.
Real mock objects, and not just simple stubs, allow you to control their behavior. This is
extremely important when mocking heavyweight resources such as DAOs. Because you are
testing against a mock DAO, there is no database, so how does the DAO retrieve any objects?
Mocks can be told not only how to look (what interface to appear as) but how to act. In other
words, you instruct a mock object what to do when certain methods are called. When mocking
a DAO, for instance, you can easily say, “When the method loadFoo()is called, return this
instance of Foo.”
To summarize, mock objects are used when you need to either replace a heavyweight
dependency with a lightweight instance just for testing, or when you need to use an intelligent
stub. Those two situations often occur simultaneously, making mock objects a perfect addi-
tion to any testing tool belt.
Let’s move on to some concrete examples showing off how mock objects work with real tests.
Unit Tests with jMock
For the AccountServiceImpltest we will create a mock for AccountDaoin order to return
an Accountinstance we can control. To begin, the superclass for the test will be org.jmock.
MockObjectTestCaseinstead of junit.framework.TestCase. This is not required; however, it
makes using jMock much easier and is recommended. The MockObjectTestCaseclass provides
helper methods used when creating the mock instance, and not using it simply means that
configuring mocks will be more verbose.
Let’s begin by setting up the test class, creating an instance of AccountServiceImpland a
mock AccountDao, shown in Listing 10-5.
CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS 293