Java Reference
In-Depth Information
private Map makeParameters(Address deliveryAddress,
Date deliveryTime) {
Map params = new HashMap();
params.put("zipCode", deliveryAddress.getZip();
return params;
}
}
In this example, JdoTemplate.executeFind() is passed a callback that is an
instance of an anonymous class. The callback has a doInJdo() method, which
takes a PersistenceManager as a parameter. It creates and executes a Query calling
methods such as declareVariables() that are not supported by the JdoTemplate .
Behind the scenes, the template class obtains a connection, invokes the callback,
and then releases the connection. Using a template class to execute a callback is a
lot easier than using a SessionFactoryUtil or PersistenceManagerFactoryUtil
directly because you do not have to write try/catch/finally blocks.
However, the callback-based API with instances of anonymous classes also com-
plicates testing. For example, because the findRestaurants() contains a fair
amount of code, it makes sense to use some mock object tests rather than testing
it directly against the database. A mock object test would want to verify that it
invokes JdoTemplate.executeFind() correctly. Unfortunately, it would be difficult
to define a mock object expectation that does this because executeFind() is
passed an instance of anonymous class.
Using named callback classes
A better approach, which improves testability, is to use a named callback class that
has an equals() method. The repository instantiates the callback class, passing the
query's parameters to its constructor, and executes it using the template. The
equals() method returns true if the two callback objects have the same parame-
ters. This class enables a mock object expectation to verify that the template is
invoked with the correct callback. The expectation uses the equals() methods to
compare the actual and expected callbacks. MyExampleCallback is an example of
such a callback. It implements the JdoCallback interface and defines an equals()
method that returns true if the delivery information in the two objects is the same:
class MyExampleCallback implements JdoCallback {
private final Address deliveryAddress;
private final Date deliveryTime;
 
 
 
Search WWH ::




Custom Search