Java Reference
In-Depth Information
from scratch, so you can leverage the existing data to create the initial files and then
prune the data your test cases don't need.
Even if your project is simpler and you can create the XML files from scratch in
your typical development cycle, you may face bugs that are hard to reproduce in a test
case. For instance, the user accesses a web application, executes a couple of inserts
and updates, and then a page displays a table with incorrect data. In this case, instead
of trying to reproduce all steps through code in your test case, you could just manually
reproduce the steps, then export the relevant database contents to a dataset, and
reproduce only the buggy method call in the test case.
In its simplest form, exporting a dataset is a straightforward task: all you need to do
is create a dataset object containing the data you want to export (for instance, using
DatabaseConnection.createDataset() to export the whole database or a Query-
DataSet to narrow the data) and then call a static method from the dataset format
class (like FlatXmlDataSet ):
IDataSet fullDataSet = dbunitConnection.createDataSet();
FileOutputStream xmlStream = new FileOutputStream("full-database.xml");
FlatXmlDataSet.write(fullDataSet, xmlStream);
Similarly, you could also generate the dataset's DTD :
FileOutputStream dtdStream = new FileOutputStream("full-database.dtd");
FlatDtdDataSet.write(fullDataSet, dtdStream);
This simple approach works fine most of the time, but it has a drawback: the tables
in the dataset are created in no particular order. Therefore, if one table has a for-
eign key constraint with another table, and they're generated in the wrong order,
attempts to insert the dataset into the database will mostly likely fail (because of
constraint violations).
Fortunately, the solution for this problem is also simple; all it takes is to wrap the
dataset in a FilteredDataSet that uses a DatabaseSequenceFilter , which in turn will
return the tables in the right order:
IDataSet fullDataSet = dbunitConnection.createDataSet();
ITableFilter filter = new DatabaseSequenceFilter(dbunitConnection);
FilteredDataSet filteredDatSet = new FilteredDataSet(filter, fullDataSet);
FileOutputStream xmlStream = new FileOutputStream("full-database.xml")
FlatXmlDataSet.write(fullDataSet, xmlStream);
17.7
Advanced techniques
In this section, we analyze techniques that make DbUnit usage easier to understand
and maintain. These techniques don't employ any particular DbUnit feature, just
advanced Java and JU nit API s.
17.7.1
DbUnit and the Template Design Pattern
If you look at the previous examples from a higher level, you might realize they all fol-
low the same workflow:
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search