Java Reference
In-Depth Information
E
return
getReplacedDataSet(originalDataSet, id);
}
}
[...]
public class
UserDaoJdbcImplTest
extends
AbstractDbUnitTestCase {
[...]
@Test
public void
testGetUserByIdReplacingIds()
throws
Exception {
long
id = 42;
IDataSet setupDataset = getReplacedDataSet("/user-token.xml", id);
DatabaseOperation.INSERT.execute(dbunitConnection, setupDataset);
User user = dao.getUserById(id);
assertUser(user);
}
@Test
public void
testAddUserReplacingIds()
throws
Exception {
IDataSet setupDataSet = getDataSet("/user-token.xml");
DatabaseOperation.DELETE_ALL.execute(dbunitConnection,
setupDataSet);
User user = newUser();
long
id = dao.addUser(user);
assertTrue(id>0);
IDataSet expectedDataSet = getReplacedDataSet(setupDataSet, id);
IDataSet actualDataSet = dbunitConnection.createDataSet();
Assertion.assertEquals(expectedDataSet, actualDataSet);
}
}
In the first
getReplacedDataSet()
utility method, the
ReplacementDataSet
con-
structor
B
takes as a parameter the dataset it's decorating. Notice that the original
dataset remains intact, and the method returns a new dataset. Next, we define what
must be replaced
C
, using
addReplacementObject()
(the
API
also provides an
add-
ReplacementSubstring()
method, but
addReplacementObject()
is the most com-
mon option). The second
getReplacedDataSet()
utility method gets a dataset
D
and calls the first
getReplacedDataSet()
method we defined
E
.
In the first test, the value of the
ID
F
doesn't matter, as long as the same value is
used in both places (
getReplacedDataSet()
and
getUserById()
). Next, we call
G
the new method, which reads the original
XML
file and returns a dataset with the
[ID]
dynamically replaced.
In the second test, we use
DELETE_ALL
H
to clean up the database; note that
the
ID
s are irrelevant. But if we used another
DatabaseOperation
(like
DELETE
),
we'd need to use a decorated dataset here as well. For the next part of the test
I
,
we need to use a decorated dataset in the assertion; we use the
ID
returned by the
DAO
itself. If the test still fails because of a wrong
ID
, then something is wrong with
the
DAO
class.
Next, let's look at how DbUnit handles
NULL
values.
F
G
H
I