Java Reference
In-Depth Information
has references to both the users table and the
ID
column) in sync. In the next section
we examine a better (although not yet optimal) approach, where the database infor-
mation (table and column names) is contained just in the dataset file.
17.5
Transforming data using ReplacementDataSet
DbUnit provides a simple yet powerful
IDataSet
implementation called
Replacement-
DataSet
. In the following sections, we explore how it can be used to solve some com-
mon problems.
17.5.1
Using ReplacementDataSet to handle the different IDs issue
Let's try a different approach for the “same dataset, different
ID
s” issue. Instead of
ignoring the
ID
column, couldn't we dynamically change a dataset value before the
test case uses it?
Changing the data inside a dataset would be quite complicated. Fortunately,
though, DbUnit provides the
ReplacementDataSet
class, which decorates an existing
dataset to dynamically replace tokens, according to your needs.
Back to our problem: first we need to change the dataset
XML
file, by replacing
the hardcoded
ID
s by a token (we used
[ID]
in this case, but it could anything, as
long as that string doesn't occur somewhere else in the dataset). Listing 17.10
shows the new
XML
.
Listing 17.10
user-token.xml, a dataset that uses a token for IDs
<?xml version="1.0"?>
<dataset>
<users id="[ID]" username="ElDuderino"
first_name="Jeffrey" last_name="Lebowsky" />
</dataset>
Next, we change the test case class, with the changed (and new) methods shown in
listing 17.11.
Listing 17.11
Changes on
UserDaoJdbcImplTest
to handle dynamic IDs
[...]
public class
AbstractDbUnitTestCase {
[...]
protected
IDataSet getReplacedDataSet(IDataSet originalDataSet,
int
id)
throws
Exception {
ReplacementDataSet replacementDataSet =
new ReplacementDataSet(originalDataSet);
replacementDataSet.addReplacementObject("[ID]", id);
return
replacementDataSet;
}
B
C
protected
IDataSet getReplacedDataSet(String name,
int
id)
throws
Exception{
IDataSet originalDataSet = getDataSet(name);
D