Java Reference
In-Depth Information
Prepare the database, using a dataset
XML
file.
1
Develop some Java code for the test.
2
(Optionally) Compare the state of the database with another dataset file.
3
Going further, only step 2 is specific for each test; steps 1 and 3 are the same (except
for the
XML
file locations) for all tests. In the examples so far, we achieved a level of
reuse by delegating part of step 1 to helper methods (like
getDataSet()
and
get-
ReplacedDataSet()
), but we can improve reuse even more if we use the Template
Design Pattern.
Design patterns in action: Template Method
The Template (or Template Method) is a behavioral design pattern described in
the classic GoF
10
book. In this pattern, a superclass defines the overall skele-
ton of an algorithm (that is, the template) but leaves some details to be filled
in by subclasses.
Back to our example: the template is the workflow we just described, where a super-
class defines the skeleton and takes care of steps 1 and 3, and the subclasses are
responsible for step 2.
10
The most common—and simpler—way to implement the template pattern in Java
is through an abstract superclass that implements the template and defines abstract
methods for the steps the subclasses must implement. This isn't a good approach in our
case, because it would allow each subclass to have only one test method, which in turn
would require dozens or even hundreds of test classes in a typical project.
A second approach is to create an interface that defines the steps the template
method isn't responsible for and receive an implementation (which is typically an
anonymous class) of that interface as parameter. This is the approach the Spring
Framework uses in its templates (like JdbcTemplate and HibernateTemplate), and it's
the approach used in listing 17.18.
Listing 17.18
UserDaoJdbcImplTest
using the Template Design Pattern
[...]
public class
UserDaoJdbcImplTemplatePatternTest
extends
AbstractDbUnitTestCase {
protected interface
TemplateWorker {
long
getId();
void doIt()
throws
Exception;
String getSetupDataSet();
String getAssertDataSet();
}
B
10
See
Design Patterns: Elements of Reusable Object-Oriented Software
, by Eric Gamma et al (the Gang of Four).