Testing CRUD Operations (Update)
Here is the code for testing the
update
method.
AbstractDaoTest.java (excerpt)
public void testUpdateOne() throws Exception {
runUpdateOne();
}
protected void runUpdateOne() throws Exception {
V item = getPrepopulated().get(0);
Map<String, Object> values = getObject("values");
modify(item, values);
Exception expectedException = getObject("expectedException");
try {
getSubject().update(item);
if (expectedException != null) {
fail("Exception not thrown.");
}
}
catch (Exception ex) {
if (expectedException == null || !expectedException.getClass().isAssignableFrom(ex.getClass())) {
throw ex;
}
}
}
protected abstract void modify(V item, Map<String, Object> values);
The test assumes that the database has been prepopulated with objects
of type
V
, and selects the first object
from the local cache (
getPrepopulated()
).
Next, it retrieves
"values"
from the SpringUnit context.
These values are contained in a map, which holds data values
indexed by the names of fields.
Next, the test calls
modify
to change values
in the domain model object of type
V
.
Inside the try/catch block, the test calls the
update
method
on the DAO class to persist the updated item.
There are two things to notice.
First,
modify
is an abstract method, since the manner
in which the domain model objects are altered is specific to each type.
Second, the design of this test could be improved.
The updated object could be read back from the
database and then compared against an expected value
retrieved from the SpringUnit context.
An excerpt showing the implementation of
modify
for
ProductDaoHibernateTest
follows.
ProductDaoHibernateTest.java (excerpt)
protected void modify(V item, Map<String, Object> values) {
if (values.containsKey("name")) {
item.setName((String)values.get("name"));
}
if (values.containsKey("description")) {
item.setDescription((String)values.get("description"));
}
}
AbstractDaoTest
includes tests of delete and read operations,
as well as CRUD operations that operate on lists of objects instead
of single objects.
These should be easily understandible after following these
create and update examples and then reading the code.