Database Patterns
Patterns in This Chapter
Database Sandbox 650
Stored Procedure Test 654
Table Truncation Teardown 661
Transaction Rollback Teardown 668
Database Sandbox
How do we develop and test software that depends on a database?
We provide a separate test database for each developer or tester.
Many applications use a database to store the persistent state of the application. At least some of the tests for such an application will require accessing the database. Unfortunately, a database is a primary cause of Erratic Tests (page 228 ) due to the fact that data may persist between tests. A major goal in keeping tests from interacting is ensuring that the test fixtures used by each test do not overlap. This is especially difficult when the development environment contains only a single test database and all tests run by all developers run against the same database.
A Database Sandbox is one way to keep the tests from interacting by accidentally accessing the same records in the database.
How It Works
We provide each user with a separate, self-consistent sandbox in which to work. This sandbox includes the user's own copy of any code plus—most importantly—the user's own copy of the database. Such an arrangement allows each user to modify the database in any way he or she sees fit and to exercise the application with tests without worrying about any interactions between the user's own tests and the tests conducted by other users.
When to Use It
We should use a Database Sandbox whenever we are building or modifying an application that depends on a database for a significant portion of its functionality. This need is especially evident if we have chosen to use a Shared Fixture (page 317 ). Using a Database Sandbox will help us avoid Test Run Wars (see Erratic Test ) between different users of the database. Depending on how we have chosen to implement the Database Sandbox , it may or may not allow different users to modify the structure of the database. A Database Sandbox will not prevent Unrepeatable Tests (see Erratic Test ) or Interacting Tests (see Erratic Test ), however, because it merely separates different users (and their test runs) from one another; tests within a single test run may continue to share a test fixture.
Implementation Notes
The application needs to be made configurable so that the database to be used in testing can be changed without modifying the code. Typically, this goal is accomplished by reading the database configuration information from a properties file that is customized in each user's environment.
A Database Sandbox can be implemented in many different ways. Fundamentally, the choice comes down to whether we give each user a separate database instance or just simulate one. In general, giving each user a real separate database instance is the preferred choice. This scheme may not always be feasible, however—especially if the database vendor's licensing structure makes it cost prohibitive.
Variation: Dedicated Database Sandbox
We give each developer, tester, or test user a separate database instance. This is typically accomplished by installing a lightweight database technology in each user's test environment. Examples of lightweight database technologies include MySql and Personal Oracle. The database instance can be installed on the user's own machine, on a shared test server, or on a dedicated "virtual server" running on shared server hardware.
A Dedicated Database Sandbox is the preferred solution because it provides the greatest flexibility. It allows a developer to modify the database schema, load his or her own test data, and so on.
Variation: DB Schema per Test Runner
With DB Schema per Test Runner , we give each developer, tester, or test user what appears to be a separate database instance by using built-in database support for multiple schemas.
One considerable advantage that the DB Schema per Test Runner pattern enjoys relative to the Dedicated Database Sandbox pattern is that we can share an Immutable Shared Fixture (see Shared Fixture ) defined in a common schema and put each user's mutable fixture in his or her own private schema. Note that this scheme does not allow the user to modify the structure of the database (at least not to the same degree as is possible with a Dedicated Database Sandbox ). It also forces all users, including both developers and testers, to use the same database structure. This can create logistical issues when database structure upgrades need to be rolled out.
Variation: Database Partitioning Scheme
We give each developer, tester, or test user a separate set of data within a single Database Sandbox . Each user can modify that data as he or she sees fit but is not allowed to modify the data assigned to other users.
This approach requires less database administration overhead but more data administration overhead than with the other ways to implement a Database Sandbox . Because it does not allow developers to modify the database schema, a Database Partitioning Scheme is not appropriate for evolutionary database development. It is, however, appropriate for preventing Interacting Tests when applied to different tests run from the same Test Runner . That is, we give each test a unique key such as a CustomerNumber that it uses for all data. As a consequence, other tests within the same test run use different data. This pattern can be combined with many of the other variations of Database Sandbox to prevent Interacting Tests when using a Shared Fixture . Note that this pattern does not prevent Unrepeatable Tests unless we also use Distinct Generated Values (see Generated Value on page 723 ).
Motivating Example
The following test uses Literal Values for the arguments to a constructor of a Product that is persisted into a database instance shared among several developers. The name of the Product must be unique:
public void testProductPrice_HCV() {
// Setup
Product product =
new Product( 88, // ID
"Widget", // Name
new BigDecimal("19.99")); // Price
// Exercise SUT
// ...
}
Unfortunately, we may end up with a Test Run War when we run this test against a shared database instance regardless of how effectively we tear down the Product after each test. This is because we are trying to create the same Product that the same test run from another Test Runner might be in the process of using at the same time .
Refactoring Notes
There are no code changes required of our test when we create a Dedicated Database Sandbox for each developer and tester. Therefore, tests should not have to do anything special to run completely independently of tests being run from other Test Runners (page 377 ). There is a small change required of the SUT, however, to allow the SUT to connect to different database instances based on configuration data. How we make this change varies with the technology we use and is beyond the scope of this book.
We can convert the test to use a Database Partitioning Scheme by replacing the Literal Values with calls to the appropriate getUnique method passing an ID specific to the Test Runner as a seed.
Example: Database Partitioning Scheme
Here is the same test using a Database Partitioning Scheme to ensure that each test uses a different set of products. For the getUniqueString method, we pass a string based on the MAC address of our computer.
public void testProductPrice_DPS() {
// Setup
Product product =
new Product( getUniqueInt(), // ID
getUniqueString(getMacAddress()), // Name
new BigDecimal("19.99")); // Price
// Exercise SUT
// ...
}
static int counter = 0;
int getUniqueInt() {
counter++;
return counter;
}
BigDecimal getUniqueBigDecimal() {
return new BigDecimal(getUniqueInt());
}
String getUniqueString(String baseName) {
return baseName.concat(String.valueOf( getUniqueInt()));
}
This test can now be run from several different computers against the same shared database instance without fear of a Test Run War .
Stored Procedure Test
How can we verify logic independently when we have stored procedures?
We write Fully Automated Tests for each stored procedure.
Many applications that use a database to store the persistent state of the application also use stored procedures and triggers to improve performance and do common processing on updates.
A Stored Procedure Test is a way to apply automated testing practices to this code that lives inside the database.
How It Works
We write unit tests for the stored procedures independent of the client application software. These tests may be layer-crossing tests or round-trip tests, depending on the nature of the store procedure(s) being tested.
When to Use It
We should write Stored Procedure Tests whenever we have nontrivial logic in stored procedures. This pattern will help us verify that the stored procedures—our SUT for the purposes of these tests—are working properly independently of the client application. This consideration is particularly important when more than one application will use the stored procedures or when the stored procedures are being developed by a different development team. Stored Procedure Tests are particularly important when we cannot ensure the procedures are tested adequately simply by exercising the application software (a form of Indirect Testing; see Obscure Test on page 186 ). Using Stored Procedure Tests also helps us to enumerate all the conditions under which the stored procedure could be called and what should happen in each circumstance. The very act of thinking about these circumstances is likely to improve the design—a common result of doing test-first development.
Implementation Notes
There are two fundamentally different ways to implement Stored Procedure Tests: (1) We can write the tests in the same programming language as the stored procedure and run them in the database or (2) we can write the tests in our application programming language and access the stored procedure via a Remote Proxy [GOF] . We might even write tests both ways. For example, the stored-procedure developers might write unit tests in the database programming language, whereas the application developers might prepare some acceptance tests in the application programming language to run as part of the application build.
Either way, we need to decide how the test will set up the fixture (the "before" state of the database) and verify the expected outcome (the "after" state of the database as well as any expected actions such as cascading deletes). The test may interact directly with the database to insert/verify the data (a form of Back Door Manipulation ; see page 327 ) or it could use another stored procedure (a form of round-trip test).
Variation: In-Database Stored Procedure Test
One advantage of the xUnit approach to automated testing is that the tests are written in the same language as the code we are testing. This makes it easier for the developers to learn how to automate the tests without learning a new programming language, debugger, and so on. Extending this idea to its logical conclusion, it makes sense to test stored procedures using tests that are written in the stored-procedure programming language. Naturally, we will need to run these tests inside the database. Unfortunately, that requirement may make it hard to run them as part of the Integration Build [SCM].
This variation on the Stored Procedure Test pattern is appropriate when we have more experience writing code in the stored-procedure language and/or environment than in the application environment and it is not essential that all tests be run from a single place. For example, a database or data services team that is writing stored procedures for use by other teams would find this approach attractive. Another circumstance in which it would be appropriate to use In-Database Stored Procedure Tests arises when the procedures are stored in a different source code repository than the application logic. Using In-Database Stored Procedure Test allows us to store the tests in the same repository as the SUT (in this case, the stored procedures).
In-Database Stored Procedure Tests may allow somewhat more thorough unit testing (and test-driven development) of the stored procedures because we may have better access to implementation details of the stored procedure from our tests. Of course, this violation of encapsulation could result in Overspecified Software (see Fragile Test on page 239 ). If the client code uses a data access layer, we must still write unit tests for that software in the application programming language to ensure that we handle errors correctly (e.g., failure to connect).
Some databases support several programming languages. In such a case, we can choose to use the more test-friendly programming language for our tests but write the stored procedures in the more traditional stored-procedure programming language. For example, Oracle databases support both PLSQL and Java, so we could use JUnit tests to verify our PLSQL stored procedures. Likewise, Microsoft's SQL Server supports C#, so we could use NUnit tests written in C# to verify the stored procedures written in Transact-SQL.
Variation: Remoted Stored Procedure Test
The purpose of Remoted Stored Procedure Tests is to allow us to write the tests in the same language as the unit tests for the client application logic. We must access the stored procedure via a Remote Proxy [GOF] that hides the mechanics of interacting with that procedure. This proxy can be structured as either a Service Facade [CJ2EEP] or a Command [GOF] (such as Java's JdbcOdbcCallableStatement ).
Remoted Stored Procedure Tests are, in effect, component tests in that they treat the stored procedure as a "black box" component. Because Remoted Stored Procedure Tests do not run inside the database, we are more likely to write them as round-trip tests (calling other stored procedures to set up the fixture, verify the outcome, and perform other necessary tasks) unless we have an easy way to insert or verify data. Some members of the xUnit family have extensions that are specifically intended to facilitate this behavior (e.g., DbUnit for Java and NDbUnit for .NET languages).
This solution is more appropriate if we want to keep all our tests in a single programming language. The Remoted Stored Procedure Test pattern makes it easier to run all the tests every time we check in changes to the application code.
Testing Stored Procedures with JUnit
On an early XP project, our application was mandated to use stored procedures being developed by another group. It seemed that every time we integrated our Java with those developers' PLSQL code, we found serious bugs in the fundamental behavior of their stored procedures. We were writing automated tests using JUnit for our code. Although we were sure that writing unit tests for the stored procedures would clarify the interface contract and improve the quality of the other group's code, we couldn't force the other team to write unit tests. Nor had utPLSQL even been invented at that point.
We decided to try writing unit tests for the stored procedures in the xUnit family member we were comfortable with: JUnit. Because we had to write JDBC code to access the stored procedures anyway, we defined JUnit tests for each stored procedure via the JDBC PreparedStatement classes that we had built. The tests exercised the basic behavior of the stored behaviors and a few of the more obvious failure cases. Whenever we received a new version of the stored procedures, we would run the JUnit tests before we even tried to exercise the procedures from our application code. Needless to say, many of the tests failed.
We sat down with the developers who were building the stored procedures and showed them our tests—including how they were failing left, right, and center. Needless to say, the developers were a bit embarrassed but they agreed that our tests were correct. They went off to fix the stored procedures and gave us a new version to test. The revision fared somewhat better but still produced some failures. Then a very important thing happened: The members of the other group asked for a copy of the tests we had written and instructions on how to run them for themselves. Before long, these developers were writing their own PLSQL unit tests in JUnit!
This capability is particularly useful if the stored procedures are being written and/or modified by the same team that is developing the client code. We can also use Remoted Stored Procedure Tests when another team is providing the stored procedures and we are not confident in those developers' ability to write defect-free code (probably because they are not writing In-Database Stored Procedure Tests for their code). In this situation, we can use the Remoted Stored Procedure Tests as a form of acceptance test for their code. See the sidebar " Testing Stored Procedures with JUnit " for an illustration of how this setup worked on one project.
One disadvantage of using Remoted Stored Procedure Tests is that they will likely cause the test suite to run more slowly because the tests require the database to be available and populated with data. The tests for the stored procedures can be put into a separate Subset Suite (see Named Test Suite on page 592 ) so that they need not be run with all the in-memory tests. This can significantly speed up test execution, thereby avoiding Slow Tests (page 253 ).
Remoted Stored Procedure Tests also come in handy when logic written in our programming language of choice already has unit tests and we need to move that logic into the database. By using a Remoted Stored Procedure Test , we can avoid rewriting the tests in a different programming language and Test Automation Framework (page 298 ), which can in turn save time and money. This pattern also enables us to avoid any translation errors when recoding the logic, so we can be sure the recoded logic really does produce the same results.
Motivating Example
Here is an example of a stored procedure written in PLSQL:
CREATE OR REPLACE PROCEDURE calc_secs_between (
date1 IN DATE,
date2 IN DATE,
secs OUT NUMBER
)
IS
BEGIN
secs := (date2 - date1) * 24 * 60 * 60;
END;
/
This sample was taken from the examples that come with the utPLSQL tool. In real life we might not bother testing this code because it is so simple (but then again, maybe not?) but it will work just fine to illustrate how we could go about testing it.
Refactoring Notes
This example doesn't deal so much with refactoring as with adding a missing test. Let's find a way to write one. We will see what is involved by using the two main variants: In-Database Stored Procedure Test and Remote Stored Procedure Test .
Example: In-Database Stored Procedure Test
This example uses utPLSQL, the xUnit family member for PLSQL, to automate tests that run inside the database:
CREATE OR REPLACE PACKAGE BODY ut_calc_secs_between
IS
PROCEDURE ut_setup
IS
BEGIN
NULL;
END;
PROCEDURE ut_teardown
IS
BEGIN
NULL;
END;
-- For each program to test...
PROCEDURE ut_CALC_SECS_BETWEEN
IS
secs PLS_INTEGER;
BEGIN
CALC_SECS_BETWEEN (
DATE1 => SYSDATE
'
DATE2 => SYSDATE
'
SECS => secs
);
utAssert.eq (
'Same dates',
secs,
0
);
END ut_CALC_SECS_BETWEEN;
END ut_calc_secs_between;
/
This test uses many of the familiar xUnit patterns. It is one of several tests we would normally write for this stored procedure—one test for each possible scenario. (This sample was taken from the examples that come with the utPLSQL tool. Not being a PLSQL programmer, I did not want to mess with the formatting in case it mattered!)
Example: Remoted Stored Procedure Test
To test this stored procedure in our normal programming and test execution environment, we must first find or create a Remote Proxy for it in our unit-testing environment of choice. Then we can write our unit tests in the usual manner.
The following test uses JUnit to automate tests that run outside the database and call our PLSQL stored procedure remotely:
public class StoredProcedureTest extends TestCase {
public void testCalcSecsBetween_SameTime() {
// Setup
TimeCalculatorProxy SUT = new TimeCalculatorProxy();
Calendar cal = new GregorianCalendar();
long now = cal.getTimeInMillis();
// Exercise
long timeDifference = SUT.calc_secs_between(now,now);
// Verify
assertEquals( 0, timeDifference );
}
}
We have reduced the complexity of the original test to a simple test of a function by hiding the JdbcOdbcCallableStatement behind a Service Facade. Looking at this example, it is difficult to tell that we are not testing a Java method. We would probably have additional Expected Exception Tests (see Test Method on page 348 ) to verify failed connections and other problems.
Table Truncation Teardown
How do we tear down the Test Fixture when it is in a relational database?
We truncate the tables modified during the test to tear down the fixture.
A large part of making tests repeatable and robust is ensuring that the test fixture is torn down after each test. Leftover objects and database records, as well as open files and connections, can at best cause performance degradation and at worst cause tests to fail or systems to crash. While some of these resources may be cleaned up automatically by garbage collection, others may be left hanging if they are not torn down explicitly.
Writing teardown code that can be relied upon to clean up properly in all possible circumstances is challenging and time-consuming. It involves understanding what could be left over for each possible outcome of the test and writing code to deal with that possibility. This Complex Teardown (see Obscure Test on page 186 ) introduces a fair bit of Conditional Test Logic (page 200 ) and—worst of all— Untestable Test Code (see Hard-to-Test Code on page 209 ).
When testing a system that uses a relational database, we can take advantage of the database's capabilities by using the TRUNCATE command to remove all data from a table we have modified.
How It Works
When we no longer need a persistent fixture, we issue a TRUNCATE command for each table in the fixture. It blasts all data out of the tables very efficiently with no side effects (e.g., triggers).
When to Use It
We often turn to Table Truncation Teardown when we are using a Persistent Fresh Fixture (see Fresh Fixture on page 311 ) strategy with an SUT that includes a database. It is rarely our first choice, however. That distinction goes to Transaction Rollback Teardown (page 668 ). Nevertheless, Table Truncation Teardown is a better choice for use with a Shared Fixture (page 317 ), as this type of fixture, by definition, outlives any one test. By contrast, using Transaction Rollback Teardown with a Shared Fixture would require a very long-running transaction. While not impossible, such a long-lived transaction is troublesome.
Before we can use Table Truncation Teardown, we must satisfy a couple of criteria. The first requirement is that we really want all data in the affected tables removed. The second requirement is that each Test Runner (page 377 ) has its own Database Sandbox (page 650 ). Table Truncation Teardown will not work if we are using a Database Partitioning Scheme (see Database Sandbox ) to isolate users or tests from one another. It is ideally suited for use with a DB Schema per Test Runner (see Database Sandbox ), especially when we are implementing an Immutable Shared Fixture (see Shared Fixture ) as a separate shared schema in the database. This allows us to blast away all the Fresh Fixture data in our own Database Sandbox without affecting the Immutable Shared Fixture .
If we are not using a transactional database, the closest approximation is Automated Teardown (page 503 ), which deletes only those records that were created by the test. Automated Teardown does not depend on the database transactions to do the work for it, but it does involve more development work on our part. We can also avoid the need to do teardown entirely by using Delta Assertions (page 485 ).
Implementation Notes
Besides the usual "Where do we put the teardown code?" decision, implementation of Table Truncation Teardown needs to deal with the following questions:
- How do we actually delete the data—that is, which database commands do we use?
- How do we deal with foreign key constraints and triggers?
- How do we ensure consistency when we are using an object-relational mapping (ORM)?
Some databases support the TRUNCATE command directly. Where this is the case, the obvious choice is to use this command. Oracle, for example, supports TRUNCATE . Otherwise, we may have to use a DELETE * FROM table-name command instead. The TRUNCATE or DELETE commands can be issued using In-line Teardown (page 509 —called from within each Test Method ; see page 348 ) or Implicit Teardown (page 516 —called from the tearDown method). Some people prefer to use this command with Lazy Teardown because it ensures that the tables are empty at the beginning of the test in cases where those tables would be affected by extraneous data.
Database foreign key constraints can be a problem for Table Truncation Teardown if our database does not offer something similar to Oracle's ON DELETE CASCADE option. In Oracle, if the command to truncate a table includes the ON DELETE CASCADE option, then rows dependent on the truncated table rows are deleted as well. If our database does not cascade deletes, we must ensure that the tables are truncated in the order required by the schema. Schema changes can invalidate this order, resulting in failures in the teardown code. Fortunately, such failures are easy to detect: A test error tells us that our teardown needs adjusting. Correction is fairly straightforward—typically, we just need to reorder the TRUNCATE commands. We could, of course, come up with a way to issue the TRUNCATE commands in the correct order dynamically based on the dependencies between the tables. Usually, however, it is enough to encapsulate this truncation logic behind a Test Utility Method (page 599 ).
If we want to avoid the side effects of triggers and other complications for databases where TRUNCATE is not supported, we can disable the constraints and/or triggers for the duration of the test. We should take this step only if other tests exercise the SUT with the constraints and triggers in place.
If we are using an ORM layer such as Toplink, (N)Hibernate, or EJB 3.0, we may need to force the ORM to clear its cache of objects already read from the database so that subsequent object lookups do not find the recently deleted objects. For example, NHibernate provides the ClearAllCaches method on the TransactionManager for this purpose.
Variation: Lazy Teardown
A teardown technique that works with only a few styles of Shared Fixtures is Lazy Teardown . With this pattern, the fixture must be destroyable at an arbitrary point in time. Thus we cannot depend on "remembering" what needs to be torn down; it must be obvious without any "memory." Table Truncation Teardown fits the bill because how we perform teardown is exactly the same whenever we choose to do it. We simply issue the table truncation commands during fixture setup before setting up the new fixture.
Motivating Example
The following test attempts to use Guaranteed In-line Teardown (see In-line Teardown ) to remove all the records it created:
[Test]
public void TestGetFlightsByOrigin_NoInboundFlights()
{
// Fixture Setup
long OutboundAirport = CreateTestAirport("1OF");
long InboundAirport = CreateTestAirport("1IF");
FlightDto ExpFlightDto = null;
try
{
ExpFlightDto =
CreateTestFlight(OutboundAirport, InboundAirport);
// Exercise System
IList FlightsAtDestination1 =
Facade.GetFlightsByOriginAirport( InboundAirport);
// Verify Outcome
Assert.AreEqual( 0, FlightsAtDestination1.Count );
}
finally
{
Facade.RemoveFlight( ExpFlightDto.FlightNumber );
Facade.RemoveAirport( OutboundAirport );
Facade.RemoveAirport( InboundAirport );
}
}
This code is neither easy to write nor correct! 1 Trying to keep track of the many objects the SUT has created and then tear them down one by one in a safe manner is very tricky.
Refactoring Notes
We can avoid most of the issues with coordinating In-line Teardown of multiple resources in a safe way by using Table Truncation Teardown and blasting away all the airports in one fell swoop. 2 Most of the refactoring work involves deleting the existing teardown code from the finally clause and inserting a call to cleanDatabase . We then implement this method using the truncation commands.
Example: Table Truncation (Delegated) Teardown Test
This is what the test looks like when we are done:
public void TestGetFlightsByOrigin_NoInboundFlight_TTTD()
{
// Fixture Setup
long OutboundAirport = CreateTestAirport("1OF");
long InboundAirport = 0;
FlightDto ExpectedFlightDto = null;
try
{
InboundAirport = CreateTestAirport("1IF");
ExpectedFlightDto =
CreateTestFlight( OutboundAirport,InboundAirport);
// Exercise System
IList FlightsAtDestination1 =
Facade.GetFlightsByOriginAirport(InboundAirport);
// Verify Outcome
Assert.AreEqual(0,FlightsAtDestination1.Count);
}
finally
{
CleanDatabase();
}
}
This example uses Delegated Teardown (see In-line Teardown ) to keep the teardown code visible. Normally, however, we would use Implicit Teardown by putting this logic into the tearDown method. The try/catch ensures that cleanDatabase is run but it does not ensure that a failure inside cleanDatabase will not prevent the teardown from completing.
Example: Lazy Teardown Test
Here is the same example converted to use Lazy Teardown:
[Test]
public void TestGetFlightsByOrigin_NoInboundFlight_LTD()
{
// Lazy Teardown
CleanDatabase();
// Fixture Setup
long OutboundAirport = CreateTestAirport("1OF");
long InboundAirport = 0;
FlightDto ExpectedFlightDto = null;
InboundAirport = CreateTestAirport("1IF");
ExpectedFlightDto =
CreateTestFlight( OutboundAirport, InboundAirport);
// Exercise System
IList FlightsAtDestination1 =
Facade.GetFlightsByOriginAirport(InboundAirport);
// Verify Outcome
Assert.AreEqual(0,FlightsAtDestination1.Count);
}
By moving the call to cleanDatabase to the front of the Test Method, we ensure that the database is in the state we expect it. This code cleans up whatever the last test did, regardless of whether that test provided proper teardown. It also takes care of anything added to the relevant tables since the last test was run. It has the added benefit of eliminating the need for the try/finally construct, thereby making the test simpler and easier to understand.
Example: Table Truncation Teardown Using SQL
This implementation of the cleanDatabase method uses SQL statements constructed within the code:
public static void CleanDatabase() {
string[] tablesToTruncate =
new string[] {"Airport","City","Airline_Cd","Flight"};
IDbConnection conn = getCurrentConnection();
IDbTransaction txn = conn.BeginTransaction();
try {
foreach (string eachTableToTruncate in tablesToTruncate)
{
TruncateTable(txn, eachTableToTruncate);
}
txn.Commit();
conn.Close();
} catch (Exception e) {
txn.Rollback();
} finally {
conn.Close();
}
}
private static void TruncateTable( IDbTransaction txn,
string tableName)
{
const string C_DELETE_SQL = "DELETE FROM {0}";
IDbCommand cmd = txn.Connection.CreateCommand();
cmd.Transaction = txn;
cmd.CommandText = string.Format(C_DELETE_SQL, tableName);
cmd.ExecuteNonQuery();
}
Because we are using SQL Server as the database, we had to implement our own TruncateTable method that issues a Delete * from ... SQL command. We would not have to take this step if our database implemented TRUNCATE directly.
Example: Table Truncation Teardown Using ORM
Here is the implementation of the cleanDatabase method using NHibernate, an ORM layer:
public static void CleanDatabase() {
ISession session =
TransactionManager.Instance.CurrentSession;
TransactionManager.Instance.BeginTransaction();
try {
// We need to delete only the root classes because
// cascade rules will delete all related child entities
session.Delete("from Airport");
session.Delete("from City");
session.Flush();
TransactionManager.Instance.Commit();
} catch (Exception e) {
Console.Write(e);
throw e;
} finally {
TransactionManager.Instance.CloseSession();
}
}
When using an ORM, we read, write, and delete domain objects; the tool determines which underlying tables they map to and takes the appropriate actions. Because we have chosen to make City and Airport "root" (parent) objects, any subordinate (child) objects such as the Flights are deleted automatically when the root is deleted. This approach further decouples us from the details of the table implementations.
Transaction Rollback Teardown
How do we tear down the Test Fixture when it is in a relational database?
We roll back the uncommitted test transaction as part of the teardown.
A large part of making tests repeatable and robust is ensuring that the test fixture is torn down after each test. Leftover objects and database records, as well as open files and connections, can at best cause performance degradation and at worst cause tests to fail or systems to crash. While some of these resources may be cleaned up automatically by garbage collection, others may be left hanging if they are not torn down explicitly.
Writing teardown code that can be relied upon to clean up properly in all possible circumstances is challenging and time-consuming. It involves understanding what could be left over for each possible outcome of the test and writing code to deal with this case. This Complex Teardown (see Obscure Test on page 186 ) introduces a fair bit of Conditional Test Logic (page 200 ) and—worst of all— Untestable Test Code (see Hard-to-Test Code on page 209 ).
We can avoid making any lasting changes to the database contents by not committing the transaction and taking advantage of the rollback capabilities of the database.
How It Works
Our test starts a new test transaction, sets up the fixture, exercises the SUT, and verifies the outcome of the test. Each of these steps may involve interacting with the database. At the end of the test, the test rolls back the test transaction, which prevents any of the changes from becoming persistent.
When to Use It
We can use Transaction Rollback Teardown when we are using a Fresh Fixture (page 311 ) approach with an SUT that includes a database that supports rolling back a transaction. There are, however, some prerequisites for using Transaction Rollback Teardown .
In particular, the SUT must expose methods that are normally called in the context of an existing transaction by a Humble Transaction Controller (see Humble Object on page 695 ). That is, the methods should not start their own transaction and must never commit a transaction. If we are doing test-driven development, this design will come about as a result of applying the Transaction Rollback Teardown pattern as we write our code. If we are retrofitting the tests to existing software, we may need to refactor the code to use a Humble Transaction Controller before we can use Transaction Rollback Teardown .
The nice thing about Transaction Rollback Teardown is that it leaves the database in exactly the same state as it was when we started the test, regardless of what changes we made to the database contents during the test. As a result, we do not need to determine what needs to be cleaned up and what does not. Changes to the database schema or contents do not affect our teardown logic. Clearly, this pattern is much simpler to apply than Table Truncation Teardown (page 661 ).
The usual caveats apply to any tests that run against a real database; such tests will take approximately 50 (yes, 50!) times as long to run as tests that do not access the database. This testing approach will almost surely result in Slow Tests (page 253 ) unless we replace the real database with an In-Memory Database (see Fake Object on page 551 ) for most of our tests. Because we are depending on the transactional properties of the database, a simple Fake Database (see Fake Object ) will probably not be sufficient unless it supports ACID .
Another prerequisite with Transaction Rollback Teardown is that we cannot do anything that results in a commit anywhere in the tests or the code they exercise. The sidebar " Transaction Rollback Pain " on page 670 describes examples of where commits can sneak in and cause havoc.
Transaction Rollback Pain
John Hurst sent me an e-mail in which he described some of the issues his team had encountered using Transaction Rollback Teardown . He writes:
We used Transaction Rollback Teardown for our database integration tests for a while, after a discussion on TheServerSide during which Rod Johnson advocated the approach. I gathered his main motivation for using it was for performance; a rollback is usually a lot faster than repriming the database in a new transaction for the next test. Indeed, we did find it somewhat faster than our previous approach. We used Spring's excellent AbstractTransactionalDataSourceSpringContextTests base class, which supports most of what you need to do for this pattern out of the box.
However, I chose to abandon this pattern after a few months. Here are the drawbacks I came across with this approach:
-
You lose some test isolation. In the way we implemented this pattern, anyway, each test assumed the database was in a certain base starting condition, and the rollback would revert it to that condition. In our current model, each test is responsible—usually via a base class's
setUp()— for priming the database into a known state. - You can't see what's in the database when something goes wrong. If your test fails, you usually want to examine the database to see what happened. If you've rolled back all the changes, it makes it harder to find the bug.
- You have to be very careful not to inadvertently commit during your test. Yes, the code under test has declarative transaction management, and does nothing surprising. But we occasionally would need to do things in the test setup like drop and recreate a sequence to reset its value. This, being DDL, commits any outstanding transaction—and confused programmers.
- You can't easily mix in tests that do need to commit changes. Lately I have added some PLSQL stored procedures and tests. Some of the stored procedures do explicit commits. I cannot mix these in the same JUnit suite with tests that assume the database always remains in a certain state.
I apologize if my terminology isn't consistent with what's in your book. Also, my experience is probably a little limited; I've only tried this approach in a Spring environment and I prefer to do most things in a "Spring" way. Finally, I am sure these limitations can be and are worked around in various ways. It's just that, for our team, this pattern turned out to be more trouble than it was worth.
Don't get me wrong—I DO think the pattern should be included. I just think the consequences should be noted, and maybe it isn't for everyone.
Implementation Notes
A few members of the xUnit family support Transaction Rollback Teardown directly; open-source extensions may be available for other members. If nothing is available, coding this teardown logic is not very complicated. The more significant implementation consideration is giving the tests access to nontransactional methods on the SUT. Most domain model objects are nontransactional, so this requirement should not be a problem for unit tests of domain objects. We are more likely to experience a problem when we are writing Subcutaneous Tests (see Layer Test on page 337 ) against a Service Facade [CJ2EEP] because these methods often perform transaction control. If this is the case, we will need to expose a nontransactional version of the methods by refactoring to the Humble Transaction Controller pattern. We could either use a transactional Decorator [GOF] as a separate object or simply have the transactional methods delegate to the nontransactional versions of the methods on self . This approach is called a Poor Man's Humble Object (see Humble Object ).
If the methods exist but are not visible to the client, we will need to expose them to the test. We can do so either by making the methods to be tested public or by exposing them indirectly via a Test-Specific Subclass (page 579 ). We could also do an Extract Testable Component (page 735 ) refactoring to move the nontransactional versions of the methods to a different class and make them visible to the test from there.
Any reading of the updated data in the database must occur within the context of the same transaction. This normally is not a problem except when we are trying to simulate or test concurrency. If we are using an ORM layer such as Toplink, (N)Hibernate, or EJB 3.0, we may need to force the ORM to write the changes made to the objects to the database so that methods that read the database directly (from within the same transactional context) can see them. For example, EJB 3.0 provides the EntityManager.flush static method for exactly this purpose.
Motivating Example
The following test attempts to use Guaranteed In-line Teardown (see In-line Teardown on page 509 ) to remove all the records it created:
public void testGetFlightsByOriginAirport_NoInboundFlights()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
BigDecimal inboundAirport = createTestAirport("1IF");
FlightDto expFlightDto = null;
try {
expFlightDto = createTestFlight(outboundAirport, inboundAirport);
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport( inboundAirport);
// Verify Outcome
assertEquals( 0, flightsAtDestination1.size() );
} finally {
facade.removeFlight( expFlightDto.getFlightNumber() );
facade.removeAirport( outboundAirport );
facade.removeAirport( inboundAirport );
}
}
This code is neither easy to write nor correct! 3 Trying to keep track of all objects the SUT has created and then tear them down one by one in a safe manner is very tricky.
Refactoring Notes
We can avoid most of the issues related to coordinating In-line Teardown of multiple resources in a safe way by using Transaction Rollback Teardown and blasting away all changes to the objects in one fell swoop. Most of the refactoring work consists of deleting the existing teardown code from the finally clause and inserting a call to the abortTransaction method. We also need to make the call to beginTransaction before we do any fixture setup, and we have to modify the Creation Methods (page 415 ) to ensure that they do not commit a transaction. To do so, we have them call a nontransactional version of the methods on the Service Facade.
Example: Object Transaction Rollback Teardown
Here is what the test looks like when we are done:
public void testGetFlightsByOrigin_NoInboundFlight_TRBTD()
throws Exception {
// Fixture Setup
TransactionManager.beginTransaction();
BigDecimal outboundAirport = createTestAirport("1OF");
BigDecimal inboundAirport = null;
FlightDto expectedFlightDto = null;
try {
inboundAirport = createTestAirport("1IF");
expectedFlightDto =
createTestFlight( outboundAirport, inboundAirport);
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(inboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
} finally {
TransactionManager.abortTransaction();
}
}
In this refactored test, we have replaced the multiple lines of teardown code in the finally clause with a single call to abortTransaction . We still need the finally clause because this example is using In-line Teardown ; we could easily move this call to the TransactionManager to the tearDown method because it is so generic.
In this example, Transaction Rollback Teardown undoes the fixture setup performed by the various Creation Methods we called earlier in the test. The fixture objects have not yet been committed to the database. Because getFlightsFromAirport is being called within the context of the transaction, however, it returns the newly added but not yet committed flights. (That is the "C" for "consistent" in ACID working on our behalf!)
private BigDecimal createTestAirport(String airportName)
throws FlightBookingException {
BigDecimal newAirportId =
facade._createAirport( airportName,
" Airport" + airportName,
"City" + airportName);
return newAirportId;
}
The creation method calls the nontransactional version of the facade method (an example of a Poor Man's Humble Object ):
public BigDecimal createAirport( String airportCode,
String name,
String nearbyCity)
throws FlightBookingException{
TransactionManager.beginTransaction();
BigDecimal airportId = _createAirport(airportCode, name, nearbyCity);
TransactionManager.commitTransaction();
return airportId;
}
// private, nontransactional version for use by tests
BigDecimal _createAirport( String airportCode,
String name,
String nearbyCity)
throws DataException, InvalidArgumentException {
Airport airport =
dataAccess.createAirport(airportCode,name,nearbyCity);
logMessage("CreateFlight", airport.getCode());
return airport.getId();
}
If the method we were exercising (e.g., getFlightsFromAirport ) did modify the state of the SUT and did begin and end its own transaction, we would have to do a similar refactoring on it as well.
Example: Database Transaction Rollback Teardown
The first example hid the database from the code behind a data access layer that returned or accepted objects. This is common practice when using the Domain Model [PEAA] pattern for organizing the business logic. Transaction Rollback Teardown is typically used when manipulating the database directly in our application logic (a style known as a Transaction Script [PEAA] ). The following example illustrates this approach using .NET row sets (or something similar):
[TestFixture]
public class TransactionRollbackTearDownTest
{
private SqlConnection _Connection;
private SqlTransaction _Transaction;
public TransactionRollbackTearDownTest()
{
}
[SetUp]
public void Setup()
{
string dbConnectionString = ConfigurationSettings.
AppSettings.Get("DbConnectionString");
_Connection = new SqlConnection(dbConnectionString);
_Connection.Open();
_Transaction = _Connection.BeginTransaction();
}
[TearDown]
public void TearDown()
{
_Transaction.Rollback();
_Connection.Close();
// Avoid NUnit "instance behavior" bug
_Transaction = null;
_Connection = null;
}
[Test]
public void AnNUnitTest()
{
const string C_INSERT_SQL =
"INSERT INTO Invoice(Amount, Tax, CustomerId)" +
" VALUES({0}, {1}, {2})";
SqlCommand cmd = _Connection.CreateCommand();
cmd.Transaction = _Transaction;
cmd.CommandText = string.Format(
C_INSERT_SQL,
new object[] {"100.00", "7.00", 2001});
// Exercise SUT
cmd.ExecuteNonQuery();
// Verify result
// etc.
}
}
}
This example uses Implicit Setup (page 424 ) to establish the connection and start the transaction. After the Test Method (page 348 ) has run, it uses Implicit Teardown (page 516 ) to roll back the transaction and close the connection. We assign null to the instance variables because NUnit does not create a separate Testcase Object (page 382 ) for each Test Method, unlike most other members of xUnit. See the sidebar " There's Always an Exception " on page 384 for details.