Java Reference
In-Depth Information
Although discussing the different approaches is almost a religious matter, we
assume it's a good practice to abstract data persistence to specialized classes, such as
DAO
s. The
DAO
s themselves can be implemented in many different ways:
Writing brute-force
SQL
statements (such as the
UserDaoJdbcImpl
example in
chapter 17)
■
Using third-party tools (like Apache i
BATIS
or Spring
JDBC
templates) that facil-
itate
JDBC
programming
■
Delegating the whole database access to tools that map objects to
SQL
(and
vice-versa)
■
Over the last few years, the third approach has become widely adopted, through the
use of
ORM
(object-relational mapping) tools such as Hibernate and Oracle TopLink.
ORM
became so popular that
JCP
(Java Community Process, the organization responsi-
ble for defining Java standards) created a specification
1
to address it, the
JPA
(Java Per-
sistence
API
).
JPA
, as the name states, is just an
API
; in order to use it, you need an
implementation. Fortunately, most existing tools adhere to the standard, so if you
already use an
ORM
tool (such as Hibernate), you could use it in
JPA
mode, that is,
using the Java Persistence
API
s instead of proprietary ones.
This chapter consists of two parts. First, we show how to test layers that use
DAO
s in
a multilayered application. Then we explain how to test the
JPA
-based
DAO
(data
access object) implementation, using DbUnit.
2
And although this chapter focuses on
JPA
and Hibernate, the ideas presented here
apply to other
ORM
tools as well.
18.1
Testing multilayered applications
By
multilayered
(or multitiered) application we mean an application whose structure
has been divided in layers, with each layer responsible for one aspect of the applica-
tion. A typical example is a three-tiered web application comprising of presentation,
business, and persistence layers.
Ideally, all of these layers should be tested, both in isolation (through unit tests)
and together (through integration tests). In this section, we show how to unit test the
business layer without depending on its lower tier, the persistence layer. But first, let's
look at the sample application.
18.1.1
The sample application
The examples in this chapter test the business and persistence layers (presentation
layer testing was covered in chapter 11) of an enterprise application. The persistence
layer comprises a
User
object and an
UserDao
interface, similar to those defined in
1
Some people may argue that two standards already existed before JPA: EJB entities and JDO. Well, EJB entities
were too complicated, and JDO never took off.
2
And in this aspect, this chapter is an extension of chapter 17; if you aren't familiar with DbUnit, we recom-
mend you read that chapter first.