Java Reference
In-Depth Information
complicated
API
with mock objects. It's somewhat easier to mock the i
BATIS
Sql-
MapClient
interface. Let's try that now.
Unit-testing a DAO with mock objects
Mock objects are objects that stand in place of true implementations for the pur-
pose of unit testing. Mocks don't generally have very much functionality; they sat-
isfy a single case to allow the unit test to focus on some other area without having
to worry about additional complexity. We'll use mocks in this example to demon-
strate an approach to testing the
DAO
layer.
In our example, we'll use a simple
DAO
. We'll leave out the i
BATIS
DAO
frame-
work so that we don't have to worry about transactions and such. The purpose of
this example is to demonstrate testing the
DAO
layer regardless of which
DAO
framework you use, if any at all.
First, let's consider the
DAO
we want to test. Listing 13.2 shows a
SqlMapPerson-
Dao
implementation that calls a
SQL
map similar to the example in section 13.1.1.
Listing 13.2
A simple DAO to test
public class SqlMapPersonDao implements PersonDao {
private SqlMapClient sqlMapClient;
public SqlMapPersonDao(SqlMapClient sqlMapClient) {
this.sqlMapClient = sqlMapClient;
}
public Person getPerson (int id) {
try {
return (Person)
sqlMapClient.queryForObject("getPerson", id);
} catch (SQLException e) {
throw new DaoRuntimeException(
"Error getting person. Cause: " + e, e);
}
}
}
Notice how we inject the
SqlMapClient
into the constructor of the
DAO
in
listing 13.2. This provides an easy way to unit-test this
DAO
, because we can mock
the
SqlMapClient
interface. Obviously this is a simple example, and we're not test-
ing very much at all, but every test counts. Listing 13.3 shows the unit test that will
mock the
SqlMapClient
and test the
getPerson()
method.








