Chapter 6: Chapter 6. Test-driving data access
The introduction motivates test-driving data access by highlighting the importance of persistent data, the shortcomings of manual inspection, and the gap left by faking persistence in business-logic tests.
After this chapter you will be able to
- Manual data access testing. Explain why manual visual inspection is a poor way to test data-access code.
- Data access testing challenges. Explain how data-access code’s architectural reach and third-party APIs complicate testing, and why separating these concerns matters.
- Data access layer boundaries. Trace the path from application logic through persistence logic to a relational database, including the framework or JDBC layers involved.
- Isolation of lower layers. Explain why tests ideally avoid the layer below and describe how application logic can be tested with persistence logic stubbed out.
- Persistence testing alternatives. Distinguish the alternatives for testing persistence logic and the stated tradeoff of an in-memory database.
- DAO persistence separation. Explain how a DAO interface and implementation separate persistent domain objects and their users from the underlying persistence technology.
- Unit test boundaries. Describe the criteria the author uses to distinguish unit tests from broader developer tests.
- Faking database access. Explain why the author favors faking database access rather than repeatedly hitting a database in unit tests.
- JDBC testing complexity. Explain why pure JDBC code can be cumbersome to implement and unit-test.
- DAO query test doubles. Trace how the unit test substitutes JDBC dependencies for the findByLastname query.
- JdbcTemplate responsibility split. Explain how JdbcTemplate and JdbcDaoSupport divide data-access work between the framework and the DAO developer.
- Separately tested row mapping. Describe the role of a RowMapper and how the PersonRowMapper is tested independently.
- Mocked DAO query test. Trace how the findByLastname DAO test uses a mocked JdbcTemplate and what the DAO implementation delegates to it.
- Hibernate object relational mapping. Explain how Hibernate reduces domain-object mapping boilerplate and how a field can be excluded from persistence.
- Hibernate API collaboration. Describe the roles of SessionFactory, Session, and Query in Hibernate data access, and distinguish HQL from the available SQL option.
- Mocked finder interaction. Trace the mocked interactions used to test-drive findByLastname and describe the corresponding DAO implementation.
- DAO exception handling. Explain how the example tests Hibernate failures and what additional resource concern would arise if the DAO opened its own session.
- Query duplication and verification. Explain how fuzzy matching or named queries can reduce query-string duplication in unit tests, and why real-database verification remains necessary.
- Mocks and database verification. Explain the benefits and limitations of using mock objects to test data-access code, and why executing the code against a real database matters.
- Data access integration scope. Explain what a data-access integration test connects and which components it exercises together.
- Risks Beyond Unit Tests. Explain the schema, query and object-relational mapping assumptions that unit tests can miss, and why.
- Test Database Fidelity Tradeoff. Explain why an integration test may use a different database from production and what compatibility it needs for the risks being tested.
- Production database compatibility. Explain why a substitute test database can pass integration tests while production behaves differently, and why it may still be worthwhile.
- Shared database test configuration. Describe how to make the integration-test database setup easy for a team to share and maintain.
- Database access and debugging. Distinguish the debugging access offered by standalone and embedded test databases, including a way to mitigate embedded access limitations.
- Person Persistence Test Outline. Describe the test-first outline for saving a Person through HibernatePersonDao and verifying the result.
- Separate Verification Session. Explain why the test verifies persistence using a new Hibernate Session rather than reusing the current one.
- Layered Hibernate Test Configuration. Explain how the test SessionFactory configuration layers testing properties over production properties and why.
- In-Memory Database And Schema. Describe the test configuration for an in-memory HSQLDB and how Hibernate creates and removes its schema.
- Versioned SQL schema definitions. Explain why the schema should be versioned with the code and describe the benefits and difficulties of defining it in SQL scripts.
- Hibernate schema generation tradeoffs. Describe how Hibernate creates the integration-test schema from mappings and explain the limitations of its generated column types.
- Incremental schema changes. Explain how ordered, reversible DDL changes support schema versioning and why database rollback differs from rolling back application code.
- Hibernate DAO save implementation. Trace how HibernatePersonDao uses its supplied SessionFactory to save a Person to the underlying database.
- Transactional fixture isolation. Explain why database integration tests need a stable state and how a transactional fixture restores it after each test.
- Data for read integration tests. Explain why an integration test for a read operation such as findByLastname needs data in the database.
- Hibernate test data population. Describe how the example populates the database with Hibernate before testing the DAO’s finder method.
- Test data proximity. Explain why placing test data alongside test logic makes the finder test easier to understand.
- ORM population tradeoffs. Explain the limitations of relying on an ORM to populate integration-test data.
- DbUnit test fixture setup. Describe how a DbUnit integration test establishes a known database state and runs data-access code against it.
- Flat XML data sets. Explain how DbUnit's flat XML represents database rows and the trade-off of keeping test data in external files.
- Database contents comparison. Trace how a test compares actual database contents with an expected data set, and describe how to limit the comparison to relevant tables.
- Test First Development Drivers. Explain how TDD differs from traditional testing stages and how unit and integration tests can both drive production code.
- DbUnit test driven cycle. Trace the DbUnit TDD cycle from writing a test through resolving missing data and any schema problems, implementing functionality, and reaching a green bar.
- Integration cycle tradeoffs. Distinguish the integration-test cycle from unit-test TDD in terms of speed, additional steps, and possible refactoring.
- Integration testing toolset. Explain the initial plumbing cost of integration tests and the toolset that makes data-access TDD practical.
- Database Integration Test Tradeoffs. Explain what integration tests reveal about data-access code and how their execution time affects development.
- Test Doubles for Difficult Cases. Explain why unit tests with test doubles can be easier than integration tests for certain data-access scenarios, using an example.
- Complementary Test Selection. Justify using both unit and integration tests for data-access development rather than choosing one exclusively.
- Stream-Based File Abstraction. Explain how streams, Reader, or Writer can reduce file-system access in tests and why this is useful.
- Storage abstraction in downloader tests. Explain how the ContentStorage interface separates the downloader’s file operations from disk access in tests, and describe why the real implementation still receives focused tests.
- File access isolation. Explain why file access should be encapsulated behind a custom interface used by the rest of the code.
- Streams for file contents. Explain why code that only needs file contents, such as a diff operation, can accept streams instead of file objects.
- Custom file object interfaces. Describe when a custom file interface is useful instead of streams alone and how it makes file-oriented code testable.
What it builds on
- Test doubles stand in for dependencies (chapter 4) · Test doubles can stand in for dependencies.
- State and interaction-based testing (chapter 4) · Tests can verify interactions with a dependency.
- Stubs, fakes, and mocks (chapter 4) · Stubs and mocks are kinds of test doubles.
- Isolate dependencies (chapter 4) · Isolating dependencies from the code that uses them.
- Inject dependencies (chapter 4) · Dependencies can be supplied to the object under test.
- Mock objects in action (chapter 4) · Using mock objects to test collaboration
- Expecting an exception (chapter 2) · Testing for an expected exception
- Expecting details from an exception (chapter 2) · Checking details of an exception
Section by section
Introduction
The introduction motivates test-driving data access by highlighting the importance of persistent data, the shortcomings of manual inspection, and the gap left by faking persistence in business-logic tests.
- Manual data access testing: Explain why manual visual inspection is a poor way to test data-access code.
Why it matters: This explains why data access deserves a more reliable approach to testing. - Faked versus actual persistence: Distinguish testing business logic with faked persistence services from implementing the persistence layer itself.
Why it matters: This distinction identifies the data-access work that earlier business-logic tests left open.
Key terms: persistent data, data-access code, visual inspection, test doubles, business logic, persistence services, persistence layer
6.1 Exploring the problem domain
This section explains why data-access code presents distinctive testing challenges.
- Data access testing challenges: Explain how data-access code’s architectural reach and third-party APIs complicate testing, and why separating these concerns matters.
Why it matters: Recognizing these challenges helps you understand why data access needs a testable design.
Key terms: data-access code, layers, third-party APIs
6.1.1 Data access crosses boundaries
This section maps the layers involved in data access and introduces the testing choices created by their boundaries.
- Data access layer boundaries: Trace the path from application logic through persistence logic to a relational database, including the framework or JDBC layers involved.
Why it matters: The layers show where a test can encounter dependencies beyond the code being developed. - Isolation of lower layers: Explain why tests ideally avoid the layer below and describe how application logic can be tested with persistence logic stubbed out.
Why it matters: Isolating the layer under development can make tests easier to run and write. - Persistence testing alternatives: Distinguish the alternatives for testing persistence logic and the stated tradeoff of an in-memory database.
Why it matters: The persistence layer presents a choice between isolating its dependencies and testing against a database.
Key terms: application logic, persistence logic, persistence framework, JDBC API, JDBC driver, relational database, unit test, coupling, stub, persistence logic layer interface
6.1.2 Separating layers with the DAO pattern
This section explains how the DAO pattern separates application code from persistence technology and how persistence libraries reduce data-access plumbing.
- DAO persistence separation: Explain how a DAO interface and implementation separate persistent domain objects and their users from the underlying persistence technology.
Why it matters: This separation keeps persistence details out of application code and makes the storage technology replaceable. - Persistence framework plumbing: Describe how persistence frameworks and support libraries reduce the work involved in data access alongside the DAO pattern.
Why it matters: Using a suitable library can reduce repetitive data-access work beyond the separation provided by DAOs.
Key terms: Data Access Object, DAO, persistent domain object, PersonDao, persistence technology, persistence frameworks, Hibernate, JdbcTemplate, persistence logic, plumbing
6.2 Driving data access with unit tests
This section frames unit-testing data access by identifying the maintenance cost of scattered JDBC code and explaining why unit tests should avoid real external dependencies.
- Scattered JDBC maintenance cost: Explain why scattering raw JDBC calls throughout a codebase makes database changes harder to maintain.
Why it matters: Keeping data-access code from spreading makes database changes less disruptive. - Unit test boundaries: Describe the criteria the author uses to distinguish unit tests from broader developer tests.
Why it matters: These boundaries clarify what the author means by unit testing data-access code. - Faking database access: Explain why the author favors faking database access rather than repeatedly hitting a database in unit tests.
Why it matters: Avoiding repeated database access helps keep unit tests fast.
Key terms: JDBC, data-access code, unit tests, developer tests, test double, database
6.2.1 Witnessing the tyranny of the JDBC API
This section test-drives a pure JDBC DAO with test doubles to illustrate the complexity of testing JDBC code and the need to verify resource cleanup.
- JDBC testing complexity: Explain why pure JDBC code can be cumbersome to implement and unit-test.
Why it matters: This explains why a seemingly simple data-access test can become large. - DAO query test doubles: Trace how the unit test substitutes JDBC dependencies for the findByLastname query.
Why it matters: Tracing the dependency chain shows how the DAO can be exercised without a database. - Result set test data: Describe why the test uses a fake ResultSet and how it checks the returned people.
Why it matters: The fake keeps the test focused on the people returned rather than every result-reading call. - Exceptional resource cleanup: Explain the cleanup limitation of the passing implementation and the additional tests it needs.
Why it matters: A passing happy-path test does not establish that database resources are released after failures.
Key terms: JDBC, plumbing code, checked exceptions, resources, PersonDao, findByLastname, DataSource, Connection, PreparedStatement, ResultSet
6.2.2 Reducing pain with Spring’s JdbcTemplate
This section shows how Spring’s JdbcTemplate simplifies JDBC code and how to test-drive a DAO and its row mapper using mocks and EasyMock argument matchers.
- JdbcTemplate responsibility split: Explain how JdbcTemplate and JdbcDaoSupport divide data-access work between the framework and the DAO developer.
Why it matters: This separation makes data-access code and its tests smaller and easier to maintain. - Separately tested row mapping: Describe the role of a RowMapper and how the PersonRowMapper is tested independently.
Why it matters: Testing the conversion separately keeps the DAO test focused on query behavior. - Mocked DAO query test: Trace how the findByLastname DAO test uses a mocked JdbcTemplate and what the DAO implementation delegates to it.
Why it matters: The example shows how to test query delegation without directly exercising JDBC resource handling. - EasyMock argument matching: Explain why the DAO test uses EasyMock argument matchers and distinguish eq, aryEq, and isA.
Why it matters: Choosing the right matcher lets the mock verify meaningful query arguments, including arrays.
Key terms: JdbcTemplate, JdbcDaoSupport, boilerplate, RowMapper, ResultSet, PersonRowMapper, findByLastname, query, EasyMock, eq
6.2.3 Closer to test-driven nirvana with Hibernate
This section explains Hibernate’s main abstractions and demonstrates test-driving a DAO with mocks, including exception handling and the limits of mocked query tests.
- Hibernate object relational mapping: Explain how Hibernate reduces domain-object mapping boilerplate and how a field can be excluded from persistence.
Why it matters: Automatic mapping reduces the code you must maintain when domain objects change. - Hibernate API collaboration: Describe the roles of SessionFactory, Session, and Query in Hibernate data access, and distinguish HQL from the available SQL option.
Why it matters: These interfaces provide the collaboration a Hibernate DAO uses and its unit test can mock. - SessionFactory configuration options: Describe the two ways presented to configure a SessionFactory and their respective testing considerations.
Why it matters: The configuration approach affects how easily test and production setups can be maintained. - Mocked finder interaction: Trace the mocked interactions used to test-drive findByLastname and describe the corresponding DAO implementation.
Why it matters: The test drives the DAO’s collaboration with Hibernate without touching a database. - DAO exception handling: Explain how the example tests Hibernate failures and what additional resource concern would arise if the DAO opened its own session.
Why it matters: Testing failure behavior helps prevent lost causes and, where the DAO owns sessions, leaked resources. - Query duplication and verification: Explain how fuzzy matching or named queries can reduce query-string duplication in unit tests, and why real-database verification remains necessary.
Why it matters: A mock can confirm interactions while allowing an incorrect database query to go undetected.
Key terms: object-relational mapping, Hibernate, persistent fields, transient, RowMapper, SessionFactory, Session, Query, HQL, SQL
6.3 Writing integration tests before the code
This section explains why data-access unit tests with mocks cannot replace checking the code and persistence framework against a real database.
- Mocks and database verification: Explain the benefits and limitations of using mock objects to test data-access code, and why executing the code against a real database matters.
Why it matters: This distinction explains why passing mock-based tests alone does not establish that data access works with the actual database.
Key terms: data-access objects, test doubles, mock objects, expectations, persistence framework, integration tests
6.3.1 What is an integration test?
This section explains data-access integration tests, the risks they catch beyond unit tests, and why a faster test database can differ from production.
- Data access integration scope: Explain what a data-access integration test connects and which components it exercises together.
Why it matters: This defines what the integration test adds to isolated tests of data-access code. - Risks Beyond Unit Tests: Explain the schema, query and object-relational mapping assumptions that unit tests can miss, and why.
Why it matters: These gaps explain why a passing unit-test suite may still leave data-access failures undiscovered. - Test Database Fidelity Tradeoff: Explain why an integration test may use a different database from production and what compatibility it needs for the risks being tested.
Why it matters: This helps balance quick TDD feedback with meaningful checks of data-access assumptions.
Key terms: integration tests, persistence logic, persistence framework, relational database, database schema, domain model, query statements, object-relational mappings, mock objects, production environment
6.3.2 Selecting the database
This section weighs production compatibility, team setup, and debugging access when selecting a database for integration tests.
- Production database compatibility: Explain why a substitute test database can pass integration tests while production behaves differently, and why it may still be worthwhile.
Why it matters: A fast test database is useful only if you understand the compatibility risks it introduces. - Application side identifier generation: Explain how generating identifiers in the persistence layer can reduce database-specific compatibility problems and what complexity it introduces.
Why it matters: Identifier generation is a concrete example of trading database dependence for application complexity. - Shared database test configuration: Describe how to make the integration-test database setup easy for a team to share and maintain.
Why it matters: A shared, automated setup makes it easier for the whole team to run the tests consistently. - Database access and debugging: Distinguish the debugging access offered by standalone and embedded test databases, including a way to mitigate embedded access limitations.
Why it matters: Convenient access to test data can make a difficult integration-test failure much easier to investigate.
Key terms: JDBC, reserved words, UNIQUE constraints, production database, persistence layer, unique identifiers, sequence generator, primary-key generators, configuration management system, automated build scripts
6.4 Integration tests in action
This section introduces a Hibernate integration-testing example, from persisting an object to maintaining test data with transactional fixtures.
6.4.1 Writing our first Hibernate integration test
This section sketches a Hibernate DAO integration test and configures it to run against an in-memory database.
- Representative Database Test Coverage: Explain why a representative subset of similar persistence operations can be tested against a database while other cases use unit tests with doubles.
Why it matters: This balance keeps useful database coverage without making the entire test suite unnecessarily slow. - Person Persistence Test Outline: Describe the test-first outline for saving a Person through HibernatePersonDao and verifying the result.
Why it matters: The outline makes the intended persistence behavior concrete before the DAO exists. - Separate Verification Session: Explain why the test verifies persistence using a new Hibernate Session rather than reusing the current one.
Why it matters: A fresh verification session helps prevent a test from mistaking uncommitted changes for successful persistence. - Layered Hibernate Test Configuration: Explain how the test SessionFactory configuration layers testing properties over production properties and why.
Why it matters: Reusing production settings while overriding test-specific ones helps catch integration issues without duplicating the whole configuration. - In-Memory Database And Schema: Describe the test configuration for an in-memory HSQLDB and how Hibernate creates and removes its schema.
Why it matters: A dedicated in-memory database gives the test a local target and requires an initialized schema.
Key terms: integration tests, unit tests, test doubles, HibernatePersonDao, Person, SessionFactory, transient, ID, Session, transaction
6.4.2 Creating the database schema
This section compares ways to version, create, and incrementally change a database schema for integration testing and deployment.
- Versioned SQL schema definitions: Explain why the schema should be versioned with the code and describe the benefits and difficulties of defining it in SQL scripts.
Why it matters: Treating the schema as versioned code helps keep database structure aligned with the application. - Hibernate schema generation tradeoffs: Describe how Hibernate creates the integration-test schema from mappings and explain the limitations of its generated column types.
Why it matters: Automatic schema creation simplifies test setup, but its defaults can conceal differences from the intended production schema. - Incremental schema changes: Explain how ordered, reversible DDL changes support schema versioning and why database rollback differs from rolling back application code.
Why it matters: Incremental changes offer a way to move between schema versions while respecting existing data. - dbdeploy delta script management: Describe how dbdeploy orders delta scripts, identifies rollback statements, and tracks which changes have been applied.
Why it matters: This example shows how a tool can organize and track incremental database changes.
Key terms: database schema, DDL, SQL scripts, version control, Hibernate, SessionFactory, mapping documents, hibernate.hbm2ddl.auto=create-drop, sql-type, incremental DDL scripts
6.4.3 Implementing the production code
This section implements HibernatePersonDao to persist a Person using a SessionFactory and a transaction.
- Hibernate DAO save implementation: Trace how HibernatePersonDao uses its supplied SessionFactory to save a Person to the underlying database.
Why it matters: This connects the integration test’s persistence expectation to the DAO’s implementation.
Key terms: HibernatePersonDao, SessionFactory, Session, transaction, save(person)
6.4.4 Staying clean with transactional fixtures
This section explains how transactional fixtures preserve database state between integration tests, along with their performance benefit and limitation.
- Transactional fixture isolation: Explain why database integration tests need a stable state and how a transactional fixture restores it after each test.
Why it matters: Restoring the fixture keeps one test’s database changes from disrupting the next. - Fixture performance advantage: Explain why transactional fixtures can be faster than repopulating the database before every test.
Why it matters: Avoiding repeated database population can make a large integration-test suite faster. - Committed transaction limitation: Explain why a transactional fixture cannot test code that commits the ongoing transaction.
Why it matters: This limitation prevents relying on rollback cleanup when the behavior under test commits the transaction.
Key terms: transactional fixture, fixture, Transaction, Session, setUp, tearDown, transactional fixtures, known state, test database, transactional behavior
6.5 Populating data for integration tests
The section explains why integration tests of database reads need test data and notes the limitations of populating it with SQL scripts.
- Data for read integration tests: Explain why an integration test for a read operation such as findByLastname needs data in the database.
Why it matters: Real database reads need data to read when the persistence results are not faked. - SQL script population tradeoffs: Describe the limitations of using SQL INSERT scripts to populate an integration test database.
Why it matters: Recognizing these drawbacks helps explain why the book considers alternatives to SQL scripts.
Key terms: integration test, read operation, persistence framework, SQL scripts, INSERT statements, portable
6.5.1 Populating objects with Hibernate
This section shows how to populate integration-test data with Hibernate and explains the approach’s benefits and limitations.
- Hibernate test data population: Describe how the example populates the database with Hibernate before testing the DAO’s finder method.
Why it matters: This lets you prepare database-backed test data using the same objects as your Java application. - Test data proximity: Explain why placing test data alongside test logic makes the finder test easier to understand.
Why it matters: Visible test data makes it easier to understand why a test expects a particular result. - ORM population tradeoffs: Explain the limitations of relying on an ORM to populate integration-test data.
Why it matters: These tradeoffs help you decide when ORM-based setup may not be sufficient or practical.
Key terms: Hibernate API, object graphs, flushing the session, findByLastname, test data, test logic, external SQL file, object-relational mappings, persistence framework, raw SQL
6.5.2 Populating data with DbUnit
This section shows how to use DbUnit to populate a known database state from external data and compare database contents with expected data.
- DbUnit test fixture setup: Describe how a DbUnit integration test establishes a known database state and runs data-access code against it.
Why it matters: A known starting state makes it possible to check data-access behavior against predictable data. - Flat XML data sets: Explain how DbUnit's flat XML represents database rows and the trade-off of keeping test data in external files.
Why it matters: Understanding the format lets you read and maintain the data that establishes a test's starting state. - Database contents comparison: Trace how a test compares actual database contents with an expected data set, and describe how to limit the comparison to relevant tables.
Why it matters: Comparing expected and actual database contents provides a direct way to check data-access changes.
Key terms: DatabaseTestCase, DatabaseConnection, DbUnitIntegrationTestCase, data set, flat XML, dataset, table, column, IDataSet, Assertion
6.6 Should I drive with unit or integration tests?
This section contrasts test-first development with traditional testing stages and introduces unit and integration tests as ways to drive implementation.
- Test First Development Drivers: Explain how TDD differs from traditional testing stages and how unit and integration tests can both drive production code.
Why it matters: Both kinds of tests can help you write code test-first, even though they shape development differently.
Key terms: test-driven development, unit tests, test doubles, integration tests
6.6.1 TDD cycle with integration tests
This section describes the integration-test TDD cycle, including DbUnit’s extra data and schema steps and the tools needed to keep the cycle practical.
- DbUnit test driven cycle: Trace the DbUnit TDD cycle from writing a test through resolving missing data and any schema problems, implementing functionality, and reaching a green bar.
Why it matters: This cycle shows how database-related failures become part of the test-driven workflow. - Integration cycle tradeoffs: Distinguish the integration-test cycle from unit-test TDD in terms of speed, additional steps, and possible refactoring.
Why it matters: Recognizing the longer feedback loop helps you understand the tradeoffs of driving data access with integration tests. - Integration testing toolset: Explain the initial plumbing cost of integration tests and the toolset that makes data-access TDD practical.
Why it matters: The right infrastructure reduces the friction of adding and maintaining integration tests.
Key terms: DbUnit, data files, database schema, green bar, integration tests, unit test–based TDD, green states, database refactorings, plumbing, persistence framework
6.6.2 Best of both worlds
This section weighs integration tests against unit tests for data access and recommends using both according to the task.
- Database Integration Test Tradeoffs: Explain what integration tests reveal about data-access code and how their execution time affects development.
Why it matters: This tradeoff helps you value database-level feedback without overlooking the cost of waiting for it. - Test Doubles for Difficult Cases: Explain why unit tests with test doubles can be easier than integration tests for certain data-access scenarios, using an example.
Why it matters: Test doubles make some failure cases and test setups much easier to exercise. - Complementary Test Selection: Justify using both unit and integration tests for data-access development rather than choosing one exclusively.
Why it matters: Choosing the right test for each task lets you benefit from both approaches.
Key terms: integration tests, unit tests, data-access code, test doubles, integration test, domain objects, golden middle ground
6.7 File-system access
This section explains why unit tests should minimize file-system access and use stream abstractions to supply file data.
- Unit Test Independence: Explain the unit-test rules for file-system access, parallel execution, and environmental setup, and why they matter.
Why it matters: These constraints keep unit tests fast and maintainable. - Stream-Based File Abstraction: Explain how streams, Reader, or Writer can reduce file-system access in tests and why this is useful.
Why it matters: Passing data through an abstraction can keep tests focused on the content without unnecessarily touching the file system.
Key terms: unit test, file system, speed, maintainability, streams, java.io.Writer, java.io.Reader, file system access
6.7.1 A tale from the trenches
This section illustrates how a storage interface makes a background content downloader easier to unit-test without frequent file-system access.
- Storage abstraction in downloader tests: Explain how the ContentStorage interface separates the downloader’s file operations from disk access in tests, and describe why the real implementation still receives focused tests.
Why it matters: Separating storage operations from their disk implementation lets most tests run without file-system setup and cleanup.
Key terms: ContentStorage, ContentDownload, unit tests, file I/O
6.7.2 Practices for testable file access
This section presents design and test-fixture practices that make file-access functionality easier to test.
- File access isolation: Explain why file access should be encapsulated behind a custom interface used by the rest of the code.
Why it matters: Isolating file access can make changes easier to test without building a whole directory structure. - Streams for file contents: Explain why code that only needs file contents, such as a diff operation, can accept streams instead of file objects.
Why it matters: Accepting streams can remove unnecessary physical-file setup from tests. - Custom file object interfaces: Describe when a custom file interface is useful instead of streams alone and how it makes file-oriented code testable.
Why it matters: A file abstraction lets code use metadata without forcing tests to manipulate real files. - Dedicated temporary test directory: Explain how a dedicated temporary directory simplifies tests that must generate physical files.
Why it matters: Keeping test files together makes cleanup simpler. - Cleanup before each test: Explain why it can be useful to clean up before each test rather than immediately afterward.
Why it matters: Preserving generated files can make a difficult failure easier to investigate.
Key terms: file access, custom interface, stream objects, file handles, FileInputStream, custom file interface, façade, metadata, Jakarta Commons VFS, virtual file system
6.8 Summary
Where this is used later
- Accelerating test execution (chapter 11) · Using transactional fixtures to keep database tests clean.
- Managing test data (chapter 11) · Populating objects with Hibernate provides context for using domain objects and an ORM to generate data.
Concepts explained in this chapter
- integration testAn integration test checks whether multiple software components work together correctly.
- HibernateHibernate is a Java object-relational mapping framework that maps Java objects to relational database structures and supports their persistence.
- Hibernate sessionA Hibernate Session is an interface for interacting with a database and managing persistent objects within a persistence context.
- SessionFactorySessionFactory is a Hibernate interface that creates and provides database sessions.
- JdbcTemplateJdbcTemplate is a Spring Framework class that provides higher-level JDBC operations while managing repetitive data-access and resource-handling tasks.
- JDBCJDBC is Java's standard API for connecting to databases, executing SQL statements, and processing results.
- HSQLDBHSQLDB is an open-source relational database management system written in Java that supports embedded and server modes.
- RowMapperRowMapper is a Spring interface for converting a row of database results into an object.
- file accessFile access is the reading or writing of data through files in a file system.
- data access objectA data access object encapsulates access to a data source behind an interface used by application code.
- in-memory databaseAn in-memory database is a database that stores its data primarily in main memory rather than on persistent storage.
- datasetA dataset is a collection of related data values treated together for comparison or analysis.
- data access codeData access code retrieves, stores, or otherwise interacts with data in storage systems or services.
- transactional fixtureA test fixture whose database changes are enclosed in a transaction that is rolled back during teardown to restore the starting state.
- unit testUnit testing is the practice of checking individual units of code, typically in isolation.
- data definition languageA data definition language is a language for declaring and modifying database structures such as tables and columns.
- incremental DDL scriptAn incremental DDL script is a small database schema change that can be applied as a step in an ordered sequence of changes.
- file access interfaceA file access interface is an application-defined abstraction that exposes file operations while hiding their underlying implementation.
- test cleanupTest cleanup is the removal or reset of files and other state created during test execution.
- test doubleA test double is a substitute for a real collaborator used to provide controlled or recorded interactions in a test.
- fake instanceA fake is a test double with a simplified working implementation that substitutes for a real collaborator.
- testabilityThe degree to which software can be readily instantiated, exercised, and verified through tests.
- custom argument matchingCustom argument matching is a technique for checking method-call arguments with criteria other than the arguments' default equality comparison.
- test-driven developmentTest-driven development is a software development technique in which tests are written before the code they guide and verify.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
