Java Reference
In-Depth Information
Listing 13.3
A unit test for the PersonDao with a mock SqlMapClient
public void testShouldGetPersonFromDaoWithIDofOne() {
final Integer PERSON_ID = new Integer(1);
Mock mock = new Mock(SqlMapClient.class);
mock.expects(once())
.method("queryForObject")
.with(eq("getPerson"),eq(PERSON_ID))
.will(returnValue(new Person (PERSON_ID)));
PersonDao daoSqlMap =
new SqlMapPersonDao((SqlMapClient) mock.proxy());
Person person = daoSqlMap.getPerson(PERSON_ID);
assertNotNull("Expected non-null person instance.",
person);
assertEquals("Expected ID to be " + PERSON_ID,
PERSON_ID, person.getId());
}
The example in listing 13.3 uses the
JU
nit as well as the
JM
ock object-mocking
framework for Java. As you can see in the bolded section, mocking the
SqlMapCli-
ent
interface with
JM
ock allows us to test the behavior of the
DAO
without worry-
ing about the actual
SqlMapClient
, including the
SQL
, the
XML
, and the database
that comes along with it.
JM
ock is a handy tool that you can learn more about at
www.jmock.org. As you might have already guessed, there is also a mocking frame-
work for .
NET
called
NM
ock, which you can find at http://nmock.org.
13.1.3
Unit-testing DAO consumer layers
The other layers of your application that use the
DAO
layer are called
consumers
.
The
DAO
pattern can help you test the functionality of those consumers without
depending on the full functionality of your persistence layer. A good
DAO
imple-
mentation has an interface that describes the available functionality. The key to
testing the consumer layer lies in having that interface. Consider the interface in
listing 13.4; you may recognize the
getPerson()
method from the previous section.
Listing 13.4
Simple DAO interface
public interface PersonDao extends Dao {
Person getPerson(Integer id);
}
















