Testing CRUD Operations (Create)
The implementations of CRUD operations are generic and so are the tests.
Here is the code that tests the creation of a persistent domain model object
of generic type
V.
AbstractDaoTest.java (excerpt)
public void testCreateOne() throws Exception {
runCreateOne();
}
protected void runCreateOne() throws Exception {
V item = (V)getObject("item");
V expected = (V)getObject("expected");
Exception expectedException = getObject("expectedException");
try {
V actual = getSubject().create(item);
if (expectedException != null) {
fail("Exception not thrown.");
}
assertTrue(isEqual(expected, actual));
}
catch (Exception ex) {
if (expectedException == null || !expectedException.getClass().isAssignableFrom(ex.getClass())) {
throw ex;
}
}
}
The test retrieves three objects from the SpringUnit context:
an item persisted by the DAO under test, of type
V;
an expected return value of type
V;
and an expected exception.
Next, the method under test,
create, is called,
passing in the item.
As defined by the API of the Case Study, this method returns
an actual value of type
V.
Here we can see a pattern.
If the SpringUnit context contains an expected exception,
i.e.
expectedException != null,
then the test has failed, since a thrown exception
would have been trapped by the enclosing exception handler.
Otherwise, the test passes if the actual object is
equivalent to the expected object, using object (field-by-field) equality.
In the event that an exception was thrown when calling the
method under test, then the test passes if the thrown
exception is a (proper or improper) subclass of the expected exception.
If not, then the test fails due to some unexpected exception.