Java Reference
In-Depth Information
17.2
Introducing DbUnit
2002, when Java Unit testing was still in its infancy and there was no framework focused
on database testing. At about the same time, Richard Dallaway wrote an online article
titled “Unit testing database code” (
http://dallaway.com/acad/dbunit.html)
, which
inspired the creation of DbUnit.
Since then, DbUnit has became the de facto Java framework for database testing,
and its development has had its up and downs. After a period of high activity, when
most of its codebase was created, it faced a long drought. Fortunately, though, new
developers jumped in and, during the time this topic was written, several new versions
have been cut, providing many improvements and bug fixes.
Although DbUnit comprises hundreds of classes and interfaces, DbUnit usage
roughly consists of moving data to and from the database, and that data is represented
by datasets (more specifically, classes that implement the
IDataSet
interface).
In the following subsections, we examine the basic usage of datasets and some
other DbUnit artifacts.
17.2.1
The sample application
Throughout this chapter, we use DbUnit to unit test the persistence layer of a Java
application. In order to simplify, this layer consists of only the interface defined in list-
ing 17.1.
Listing 17.1
DAO interface used in the examples
public interface
UserDao {
long
addUser(User user)
throws
SQLException;
User getUserById(
long
id)
throws
SQLException;
}
The
DAO
implementation (using plain
JDBC
) isn't shown here but is available for down-
load at the topic's website. The
User
object is a simple
POJO
,
3
described in listing 17.2.
Listing 17.2
Domain model used in the examples
public class
User {
private long
id;
private
String username;
private
String firstName;
private
String lastName;
// getters and setters omitted
}
The
User
object will be mapped in the database by the users table, which can be cre-
ated using the
SQL
statement shown in listing 17.3.
2
Although it can be used without JUnit.
3
Plain old Java object.