Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Chapter 17. Testing database access > Introducing DbUnit - Pg. 329

Introducing DbUnit 329 17.2 Introducing DbUnit DbUnit (http:/ /www.dbunit.org) is a JU nit 2 extension created by Manuel LaFlamme in 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 book 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 book'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 3 Although it can be used without JUnit. Plain old Java object.