
663
Otherwise, we may have to use a DELETE * FROM table-name command instead. The TRUN-
CATE
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 reor-
der 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 dependen-
cies between the tables. Usually, however, it is enough to encapsulate this trun-
cation 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 fi nd 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 fi xture 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
fi ts 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 fi xture
setup before setting up the new fi xture.
Table
Truncation
Teardown
Table Truncation Teardown