Java Reference
In-Depth Information
Listing 17.3
SQL script that creates the users table
CREATE TABLE users (
id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1),
username VARCHAR(10),
first_name VARCHAR(10),
last_name VARCHAR(10) )
Finally, the examples will use
HSQLDB
as the database, because it's Java based and
doesn't require any further configuration.
HSQLDB
is also flexible: it can be run as cli-
ent/server or embedded, using disk or memory. The simplest—and fastest—mode is
as an in-memory embedded database, and that's the mode used in the examples.
17.2.2
Setting up DbUnit and running the sample application
DbUnit itself comprises just one
JAR
(dbunit.jar), and the only required external
dependency is the logging framework,
SLF4J
(Simple Logging Façade for Java).
SLF4J
requires two
JAR
s: slf4j-api.jar (which contains only the framework interfaces)
and an implementation, such as slf4j-nop.jar (which doesn't log anything; we talk
more about logging later on). Of course, because DbUnit will connect to a data-
base, it's also necessary to add the
JDBC
driver to the classpath; in the sample appli-
cation, it's hsqldb.jar.
The sample application is available in two flavors: Maven and Ant. To run the tests
on Maven, type
'mvn
clean
test'
. Similarly, to use Ant instead, type
'ant
clean
test'
. The application is also available as two Eclipse projects, one with the required
libraries (under the lib directory) and another with the project itself.
17.3
Using datasets to populate the database
Let's start by writing a unit test for the
getUserById()
method.
First, we need to analyze what the method does: it fetches data from the relational
database, creates a Java object, populates that object with the fetched data, and then
returns the object.
Consequently, our test case must prepare the database with the proper data, run
the code being tested, and verify that the object returned contains the expected data.
The latter two steps can be done with trivial Java code, whereas the former needs
interaction with a database—that's where DbUnit is handy.
Data in DbUnit is represented by a dataset (interface
org.dbunit.dataset.
IDataSet
), and DbUnit provides dozens of different
IDataSet
implementations, the
most common ones being
XmlDataSet
and
FlatXmlDataset
. In our example, we
need to insert a row in the table users with the values
id=1
,
username=ElDuderino
,
firstName=Jeffrey
, and
lastName=Lebowsky
. Let's see how this data could be repre-
sented on these two different dataset implementations, first in the
XmlDataSet
for-
mat (listing 17.4).