Java Reference
In-Depth Information
public void
testDeleteUserWithTelephone()
throws
Exception {
beginTransaction();
long
id = ELFunctionMapperImpl.getId(User.
class
);
dao.deleteUser(id);
commitTransaction();
}
}
Running these tests will expose the first bug in the
DAO
implementation, because
testDeleteUserWithTelephone()
fails with a constraint violation exception. Although
the user row was deleted, its telephone wasn't. The reason? Cascade deletes are taken
into account only when the
EntityManager
's
remove()
method is called, and our
DAO
used a
JPA
query to delete the user. The fix is shown in listing 18.21.
Regardless of this delete issue, the tests presented so far cover only the easy scenar-
ios: saving, loading, and deleting a simple user, with or without a telephone. It's a
good start but not enough; we need to test negative cases as well.
For the
addUser()
method, the only negative case is receiving a
null
reference.
It's always a good practice to check for method arguments and throw an
Illegal-
AccessArgumentExeption
if they don't comply. The
getUserById()
method has at
least two negative cases: handling an
ID
that doesn't exist in the database and load-
ing from an empty database. In our sample application, a
null
reference should be
returned in these cases (but another valid option would be to throw an exception).
Negative cases for
removeUser()
would be the same as for
getUserById()
, and in
our example they don't need to be tested because nothing happens when the user
doesn't exist (if an exception should be thrown, we should exercise these scenarios).
Listing 18.20 adds these new tests.
Listing 18.20
New test cases for negative scenarios
[...]
public class
UserDaoJpaImplTest
extends
AbstractJpaDbUnitELTemplateTestCase {
[...]
@Test(expected=IllegalArgumentException.
class
)
public void
testAddNullUser()
throws
Exception {
dao.addUser(
null
);
}
@Test
public void
testGetUserByIdOnNullDatabase()
throws
Exception {
getUserReturnsNullTest(0);
}
@Test
@DataSets(setUpDataSet="/user.xml")
public void
testGetUserByIdUnknownId()
throws
Exception {
getUserReturnsNullTest(666);
}
private void
getUserReturnsNullTest(
int
deltaId) {
beginTransaction();
long
id = ELFunctionMapperImpl.getId(User.
class
)+deltaId;