Java Reference
In-Depth Information
C
Testing retrieval of single
person by primary key value
public void testShouldGetPersonWithIdOfOne() {
Person person = (Person) sqlMapClient.
queryForObject("getPerson", new Integer(1));
assertNotNull("Expected to find a person.", person);
assertEquals("Expected person ID to be 1.",
new Integer(1), person.getId());
}
}
The example in listing 13.1 uses the JU nit unit-testing framework for Java. (You can
find out more about JU nit at www.junit.org. Similar tools are available for the . NET
Framework, including NU nit, which you can find at www.nunit.org.) In our setup
method , we drop and re-create our database tables and then repopulate them.
Rebuilding everything for each test ensures test isolation, but this approach may be
too slow to use on an RDBMS like Oracle or SQL Server. In cases where that is an
issue, consider an in-memory database like HSQLDB . In our actual test case , we
fetch a record, map it into a bean, and assert that the values in the bean are the val-
ues that we expected to be there.
That's all there is to testing our mapping layer. The next layer we need to test is
the DAO layer, assuming your application has one.
B
C
13.1.2
Unit-testing data access objects
The data access object layer is an abstraction layer, so by their very nature DAO s
should be easy to test. DAO s make testing consumers of the DAO layer easier as
well. In this section, we'll discuss testing a DAO itself. DAO s are generally sepa-
rated into an interface and an implementation. Because we're testing the DAO
directly, the interface does not play a role. We'll work directly with the DAO imple-
mentation for the purposes of testing. This might sound contrary to how the DAO
pattern is supposed to work, but that's the great thing about unit testing… it lets
us get bad habits out of our system!
If possible, testing at the DAO level should not involve the database or underly-
ing infrastructure. The DAO layer is an interface to the persistence implementa-
tion, but in testing a DAO we're more interested in testing what is inside the DAO
itself, not what is beyond it.
The complexity of testing a DAO depends solely on the DAO implementation.
For example, testing a JDBC DAO can be quite difficult. You'll need a good mock-
ing framework to replace all of the typical JDBC components such as Connection ,
ResultSet , and PreparedStatement . Even then, it's a lot of work managing such a
Search WWH ::




Custom Search