Java Reference
In-Depth Information
Yes, it can, so before you run the tests, you must assure that the database is in a
known state. Fortunately, there are plenty of tools that can handle this task, and in this
chapter we analyze one of them, DbUnit.
17.1.2
Unit tests must be easy to write and run
It doesn't matter how much a company, project manager, or technical leader praises
unit tests; if they're not easy to write and run, developers will resist writing them.
Moreover, writing code that accesses the database isn't the sexiest of tasks. One would
have to write SQL statements, mix many levels of try-catch-finally code, convert SQL
types to and from Java, and so on.
Therefore, in order for database unit tests to thrive, it's necessary to alleviate the
database burden on developers. Luckily again, there are tools that provide such allevi-
ation, and DbUnit is one of them.
17.1.3
Unit tests must be fast to run
Let's say you've overcome the first two issues and have a nice environment, with
hundreds of unit tests exercising the objects that access the database, and where a
developer can easily add new ones. All seems nice, but when a developer runs the
build (and they should do that many times a day, at least after updating their work-
space and before submitting changes to the source control system), it takes 10 min-
utes for the build to complete, 9 of them spent in the database tests. What should
you do then?
This is the hardest issue, because it can't always be solved. Typically, the delay is
caused by the database access per se, because the database is probably a remote
server, accessed by dozens of users. A possible solution is to move the database
closer to the developer, by either using an embedded database (if the application
uses standard SQL that enables a database switch) or locally installing lighter ver-
sions of the database.
DEFINITION Embedded database —An embedded database is a database that's
bundled within an application instead of being managed by external servers
(which is the typical scenario). A broad range of embedded databases is avail-
able for Java applications, most of them based on open source projects, such
as HSQLDB ( http://hsqldb.org) , H2 ( http://h2database.com ), Derby ( http://
db.apache.org/derby ), and Java DB ( http://developers.sun.com/javadb) .
Notice that the fundamental characteristic of an embedded database is that
it's managed by the application and not the language it's written in. For
instance, both HSQLDB and Derby support client/server mode (besides the
embedded option), although SQL ite (which is a C-based product) could also
be embedded in a Java application.
In the following sections, we show how DbUnit (and, to a lesser degree, embedded
databases) can be used to solve the database unit testing impedance mismatch.
 
 
 
 
 
 
 
Search WWH ::




Custom Search