Java Reference
In-Depth Information
User user = dao.getUserById(id);
assertNull(user);
}
E
@Test
@ExpectedDataSet("user.xml")
public void
testAddUser()
throws
Exception {
User user = newUser();
dao.addUser(user);
long
id = user.getId();
assertTrue(id>0);
}
}
In the mock example we used a custom runner to provide Unitils integration; this
time we opt to extend in
B
the proper Unitils superclass. The next step is to signal
the database module that the test case needs a data source (which in turn will be used
to configure the
DAO
); that's accomplished through the
@TestDataSource
annota-
tion, which could be used in an attribute or a method. In our case, we use it in a
method
C
, because it's necessary to pass the database connection to the
DAO
and call
the
DAO
to create the database tables;
8
otherwise, the
dbunit
module will fail when it
tries to load the datasets.
Then in
D
we have tests that load data from the database, so we use the
@DataSet
annotation to define a dataset that will be used to prepare the database before the
test. Notice that the name "
user.xml
" refers to a dataset file located in the classpath
within the same directory structure as the test class package (in our example, com/
manning/junitbook/ch19/dao/user.xml). The content of this file is the same as the
one listed in chapter 17, listing 17.5. Finally, on
E
we have a test case where data is
inserted into the database and DbUnit is used to compare the results; we use
@ExpectedDataSet
in this case.
The
JPA
example is pretty much the same; the main difference is the code to set up
the
EntityManager
and the
DAO
. Listing 19.6 shows the new test case, focusing on test
setup and showing only one test method.
Listing 19.6
Relevant changes to
UserDaoJpaImplTest
[...]
import static
com.manning.junitbook.ch19.model.EntitiesHelper.*;
import static
org.junit.Assert.*;
import
java.sql.Connection;
import
java.sql.SQLException;
import
javax.sql.DataSource;
8
If we weren't using an embedded database but rather a developer database with the tables already created,
then we could use
@TestDataSource
in a
DataSource
attribute and use a
@Before
method to pass the
connection to the DAO.