Testing Database Logic
Problem
You want to test database logic using JUnit.
Solution
Write scripts to generate a stable testing database and test against that data.
Discussion
Testing against a database is challenging in many organizations because you have to define predictable data.[29] The only truly reliable approach is to create the test data in a private database automatically for each set of tests. When the tests are finished, you should destroy the test data. If you create the test database manually, you run the risk of corruption over time as people modify data that your tests assume is present.
Tip
For very large databases, you may have to settle for either creating clean test data daily or weekly, or loading a subset of the database with well-known testing records.
We recommend that you follow the technique outlined in Recipe 4.7 to perform one-time setup and tear down before and after a group of tests. You can create the test data in the one-time setup, and remove it in the one-time tear down. Once you have control of the data, you can test against that data:
public void testDeleteEmployee( ) throws SQLException {
EmployeeDAO dao = new EmployeeDAO( );
assertNotNull("Employee 'ericBurke' should be present",
dao.getEmployee("ericBurke"));
dao.deleteEmployee("ericBurke");
assertNull("Employee 'ericBurke' should not be present",
dao.getEmployee("ericBurke"));
}Another challenge is the fact that early tests might modify data in ways that interfere with later tests. In these cases, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access