Java Reference
In-Depth Information
commitTransaction();
}
}
Because
ID
s aren't tracked by a superclass anymore, it's necessary to ask
ELFunction-
MapperImpl
B
to get the
ID
on
testLoadUserWithTelephone()
. Test case
testSave-
UserWithTelephone()
C
, on the other hand, was not changed, because it doesn't use
the
ID
s directly (only in the dataset).
18.5
Testing JPA-based DAOs
Once you're assured the persistence entities are correctly mapped, it's time to test the
application code that effectively uses
JPA
, such as
DAO
s. The test cases for
JPA
-based
DAO
s are similar to the entity mapping tests you saw in the previous section; the main
difference (besides the fact that you use
DAO
code instead of direct
JPA
calls) is that
you have to cover more scenarios, paying attention to some tricky issues.
Let's start with the simplest cases, the same cases for
getUserById()
and
addUser()
we implemented in chapter 17 (where the
DAO
s were implemented using pure
JDBC
),
plus a test case for
testRemoveUser()
. The test cases are shown in listing 18.18, and the
initial
DAO
implementation was shown in listing 18.4.
Listing 18.18
Initial version of
UserDaoJpaImplTest
[...]
public class
UserDaoJpaImplTest
extends
AbstractJpaDbUnitELTemplateTestCase {
UserDaoJpaImpl dao;
@Before
public void
prepareDao() {
dao =
new
UserDaoJpaImpl();
dao.setEntityManager(em);
}
@Test
@DataSets(setUpDataSet="/user.xml")
public void
testGetUserById()
throws
Exception {
beginTransaction();
long
id = ELFunctionMapperImpl.getId(User.
class
);
User user = dao.getUserById(id);
commitTransaction();
assertUser(user);
}
@Test
@DataSets(assertDataSet="/user.xml")
public void
testAddUser()
throws
Exception {
beginTransaction();
User user = newUser();
dao.addUser(user);
commitTransaction();
long
id = user.getId();