Java Reference
In-Depth Information
delivery address and time using the Spring and
JDO
API
s. First, we write some
mock object tests for
RestaurantRepository
. After that we write the method
and get the mock objects test to pass. Finally, we write some database tests for the
JDO
query that is executed by
RestaurantRepository
to find the restaurants.
5.3.1
Writing a mock object test for findRestaurants()
The mock objects test for
findRestaurants()
uses mock objects to verify that it
calls the Spring and
JDO
API
s correctly. But to know which objects to mock we
must decide how
findRestaurants()
executes the query. It can use either a
named query or a query that is embedded in the code. In this particular case it
makes sense to use a named query because, as you will see shortly, the query is too
large to embed inside Java code. It would be spread over several lines of code,
which would be messy.
Executing a named query using a callback class
A repository could execute a query by calling the
JDO
API
s directly, but it is usually
much easier to use the
JdoTemplate
class. It implements boilerplate code that
you would otherwise have to write and provides a number of convenience meth-
ods. However, at the time of this writing one limitation of the
JdoTemplate
class
is that it lacks a convenience method for executing named queries with parame-
ters. We must instead use it to execute a
JdoCallback
that creates and executes
the named query. Even though this requires more code than calling a conve-
nience method, it is still simpler than using the
JDO
API
s directly because the
JdoTemplate
takes care of opening and closing the
PersistenceManager
and
mapping exceptions thrown by
JDO
to Spring data access exceptions.
The most straightforward and commonly used way to use a
JdoTemplate
to
execute a
JdoCallback
is to use an anonymous class. But one big problem with
using an anonymous callback is that it's impossible for a mock
JdoTemplate
to
verify that
execute()
is called with the correct
JdoCallback
object. A better
approach is to use a named
JdoCallback
class that implements the
equals()
method because we would then be able to configure a mock
JdoTemplate
.
To implement the
findRestaurants()
method, we can define a
JdoCall-
back
class called
ExecuteNamedQueryWithMapCallback
whose constructor takes
as parameters the name of the query and the
Map
containing the query's parame-
ters. This class, shown in listing 5.4, creates the named query and returns the
result of executing it by calling
Query.executeWithMap()
. It has an
equals()
method that returns
true
if the query names and parameters are the same in the
two objects.
Search WWH ::
Custom Search