Overview

Chapter 6. Test-driving data access

To begin with, the chapter explains why data-access code deserves special test-driven treatment: it crosses architectural boundaries, depends on third-party APIs, and is often tested manually even though that is slow and error-prone. The author frames the problem in terms of designing for testability, especially by separating persistence concerns from business logic with the DAO pattern. A DAO keeps domain objects ignorant of storage details, making it easier to swap JDBC, Spring, Hibernate, or even file-based persistence without changing the application code.

The chapter then contrasts unit tests and integration tests for persistence code. For pure JDBC, test-driving can be cumbersome because the API requires lots of plumbing, so the examples rely on test doubles for DataSource, Connection, PreparedStatement, and ResultSet. Spring’s JdbcTemplate reduces that burden by hiding boilerplate behind a template method style API and a RowMapper, making tests smaller and the production code cleaner. Hibernate goes a step further by mapping objects to tables automatically, allowing DAO tests to focus on interactions with SessionFactory, Session, and Query, while also showing how to test exception handling and reduce duplication with fuzzy matching and named queries.

After unit testing, the chapter moves to integration tests to verify that the code really works against a real database schema, not just against mocked expectations. It discusses choosing a lightweight database such as an in-memory HSQLDB instance, creating schemas automatically or with scripts, and keeping tests fast by using transactional fixtures that roll back changes after each test. It also covers ways to populate test data, either through Hibernate or with DbUnit and XML datasets, and closes by comparing unit and integration tests as complementary tools rather than rivals. Finally, it briefly applies the same design principles to file-system access, recommending interfaces, streams, custom file facades, and dedicated temp directories to keep file-related code testable.

A pile of logical layers of a system. If we want to test-drive the persistence logic layer, which of the underlying layers should our tests exercise?
Data Access Object pattern: Domain objects being created, retrieved, and persisted through a Data Access Object interface without knowledge of the underlying database technology
Listing 6.2. Test for a pure JDBC DAO implementation
Collaboration between the template code provided by the Spring Framework and the DAO implementation provided by the developer
DAO implementation extends from Spring’s JdbcDaoSupport class that provides JdbcTemplate functionality
Listing 6.4. Test for the RowMapper implementation for Person objects
Listing 6.6. Full test for the JdbcTemplate-based PersonDao implementation
Listing 6.7. JdbcTemplate-based PersonDao implementation
The SessionFactory, Session, and Query interfaces represent the main concepts of the Hibernate API.
Listing 6.10. Full test for finding people by their last name
Listing 6.11. Hibernate-based implementation of the PersonDao
Listing 6.12. Testing that the session is closed even after an exception
Listing 6.14. Skeleton for our first integration test class
Listing 6.15. Configuring a SessionFactory for tests
Example directory structure with a set of delta change scripts for creating the database schema incrementally. The four scripts in the directory src/db/deltas will be applied in order according to the numerical prefix.
Listing 6.17. Example delta script with an @UNDO-block for rollback
Listing 6.18. Skeleton for our first integration test class
Listing 6.19. Integration test rolls back changes using a transactional fixture
Listing 6.20. Integration test populating data using the Hibernate API
Listing 6.21. Abstract base class for DbUnit-based integration tests
Listing 6.22. Concrete test class extending the base class from listing 6.21
Listing 6.24. Using DbUnit for comparing data sets

FAQ

What makes data-access code different from typical application logic when test-driving it?Data-access code often crosses multiple architectural layers and depends on third-party APIs that are harder to test. Because of this, tests can become slower and more tightly coupled if they involve lower layers directly. The chapter emphasizes separating concerns so the code can be tested independently and efficiently.
Why is the DAO pattern useful for test-driven development?The DAO pattern isolates persistence logic behind an interface, so application code does not need to know where data comes from or how it is stored. This makes it easier to swap persistence technologies and to test business logic without involving real databases. It also reduces scattering of data-access code throughout the system.
Why are plain JDBC implementations considered difficult to test?JDBC requires lots of plumbing code, including checked exception handling, resource closing, and interaction with several low-level interfaces such as DataSource, Connection, PreparedStatement, and ResultSet. That makes unit tests bulky and brittle, especially when trying to mock every interaction. The deeper API also makes the code harder to maintain.
How does the chapter suggest testing JDBC-based DAO code?It suggests using test doubles for JDBC interfaces. For example, a mock DataSource, Connection, and PreparedStatement can be created with EasyMock, while a fake ResultSet can be supplied to return predetermined data. The test then verifies both the returned objects and that JDBC resources are properly closed.
How does Spring’s JdbcTemplate simplify data-access code?JdbcTemplate removes much of the repetitive JDBC boilerplate and leaves the developer to focus on the query logic. It uses a template-style approach where the framework handles resource management and error handling, while the developer provides only the varying parts such as SQL, parameters, and row mapping. This results in smaller and more maintainable tests and implementations.
What is a RowMapper in Spring JDBC?A RowMapper is an object that converts a single row from a ResultSet into a domain object. In the chapter’s example, a PersonRowMapper reads first_name and last_name columns and creates a Person. Because it hides the JDBC dependency, it can be tested separately.
Why is Hibernate considered closer to “test-driven nirvana” than raw JDBC?Hibernate reduces boilerplate further by mapping domain objects to tables automatically through annotations and conventions. Developers no longer need to manually write as much code for column-to-field mapping. This makes persistence code and its tests simpler, especially when compared to low-level JDBC code.
What is the purpose of integration tests for data access?Integration tests verify that data-access code works with a real database and persistence framework, not just with mocks. They help catch issues such as schema mismatches, incorrect queries, and mapping problems that unit tests may miss. They are especially useful for confirming that the code works end to end.
What are transactional fixtures and why are they useful?Transactional fixtures start a database transaction before a test and roll it back afterward, restoring the database to its original state automatically. This keeps integration tests isolated and avoids expensive setup/teardown work for each test. The downside is that they cannot be used to test actual commit behavior.
How can test data be populated for integration tests?The chapter describes several options: using Hibernate to persist setup objects directly, using DbUnit with external XML data sets, or using SQL scripts. DbUnit is highlighted as useful for loading known database states and comparing expected versus actual data sets. The best choice depends on portability, maintainability, and how closely the test setup needs to match production.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Test Driven Test Driven ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Test Driven Test Driven ebook for free