
510
Chapter 22 Fixture Teardown Patterns
When to Use It
We should use some form of teardown logic whenever we have resources that
will not be freed automatically after the Test Method is run; we can use In-line
Teardown when each test has different objects to clean up. We may discover that
objects need to be cleaned up because we have Unrepeatable Tests (see Erratic
Test on page 228) or Slow Tests (page 253) caused by the accumulation of detritus
from many test runs.
Unlike fi xture setup, the teardown logic is not important from the perspective
of Tests as Documentation (see page 23). Use of any form of teardown logic may
potentially contribute to High Test Maintenance Cost (page 265) and should be
avoided if at all possible. Thus the only real benefi t of including the teardown logic
on an in-line basis is that it may make it easier to maintain the teardown logic—a
pretty slim benefi t, indeed. It is almost always better to strive for Automated Tear-
down (page 503) or to use Implicit Teardown (page 516) if we are using Testcase
Class per Fixture (page 631), where all tests in a Testcase Class (page 373) have the
same test fi xture.
We can also use In-line Teardown as a steppingstone to Implicit Teardown,
thereby following the principle of “the simplest thing that could possibly
work.” First, we learn how to do In-line Teardown for each Test Method; next,
we extract the common logic from those tests into the tearDown method. We
should not use In-line Teardown if the objects created by the test are subject
to automated memory management. In such a case, we should use Garbage-
Collected Teardown (page 500) instead because it is much less error-prone and
keeps the tests easier to understand and maintain.
Implementation Notes
The primary consideration in In-line Teardown is ensuring that the teardown
code actually runs even when the test is failed by an Assertion Method (page 362)
or ends in an error in either the SUT or the Test Method. A secondary consider-
ation is ensuring that the teardown code does not introduce additional errors.
The key to doing In-line Teardown correctly is to use language-level constructs
to ensure that the teardown code is run. Most modern languages include some
sort of error/exception-handling construct that will attempt the execution of a
block of code with the guarantee that a second block of code will be run regard-
less of how the fi rst block terminates. In Java, this construct takes the form of a
try block with an associated fi nally block.
In-line
Teardown