Java Reference
In-Depth Information
import
org.junit.Test;
import
org.unitils.UnitilsJUnit4;
import
org.unitils.database.annotations.TestDataSource;
import
org.unitils.dbunit.annotation.DataSet;
import
org.unitils.dbunit.annotation.ExpectedDataSet;
import
com.manning.junitbook.ch19.model.User;
public
class
UserDaoJpaImplTest
extends
UnitilsJUnit4 {
B
@JpaEntityManagerFactory(persistenceUnit="chapter-19")
@PersistenceContext
EntityManager em;
private final
UserDaoJpaImpl dao =
new
UserDaoJpaImpl();
@Before
public void
prepareDao() {
dao.setEntityManager(em);
}
C
@Test
@DataSet("user.xml")
public void
testGetUserById()
throws
Exception {
long
id = 1;
User user = dao.getUserById(id);
assertUser(user);
}
[...]
}
The only differences in this test case are that in
B
two annotations are used to mark
the
EntityManager
(which will be injected by Unitils before the tests are run), and
then in
C
the
EntityManager
is passed to our
DAO
. At
D
we have the test method
itself; notice that it's identical to the same test method in listing 19.5 (even though the
DAO
implementation is different) and similar to chapter's 18 test, except that in this
new example it isn't necessary to manage the transaction, because Unitils does that
automatically for us.
9
Besides the test classes themselves, it's necessary to set the database connection on
unitils.properties, as shown in listing 19.7.
D
Listing 19.7
unitils.properties settings for the DbUnit examples
database.driverClassName=org.hsqldb.jdbcDriver
database.url=jdbc:hsqldb:mem:my-project-test;shutdown=true
database.dialect=hsqldb
database.schemaNames=PUBLIC
unitils.modules=database,jpa,dbunit
The database information is set on
B
, and
C
lists the modules used in these tests.
Notice that
C
could be omitted, because by default Unitils uses all modules.
B
C
9
Unitils starts a transaction before each test and commits it afterward, although it could be configured to roll
back instead (through the
DatabaseModule.Transactional.value.default
property).