
505
simplest solution is to put the call to the Automated Teardown mechanism into 
the tearDown method on our Testcase Class (page 373). This method is called 
regardless of whether the test passes or fails as long as the setUp method succeeds. 
When we are tearing down a Shared Fixture (page 317), we want the tearDown
method to run only after all the Test Methods (page 348) have been run. In this 
case, we can use either Suite Fixture Setup (page 441), if our member of the 
xUnit family supports it, or a Setup Decorator (page 447). 
Now let’s go back to the harder problem: the generic mechanism for cleaning 
up the resources. We have at least two options here. First, we can ensure that all 
persistent (non-garbage-collected) objects implement a generic cleanup mechanism 
that we can call from within the Automated Teardown mechanism. Alternatively, 
we can wrap each object in another object that knows how to clean up the object 
in question. The latter strategy is an example of the Command [GOF] pattern. 
If we build our Automated Teardown mechanism in a completely generic 
way, we can include it in the Testcase Superclass (page 638) on which we can 
base all our Testcase Classes. Otherwise, we may need to put it onto a Test 
Helper (page 643) that is visible from all Testcase Classes that need it. A Test 
Helper that both creates fi xture objects and tears them down automatically is 
sometimes called an Object Mother (see Test Helper).
Being a nontrivial (and very critical) piece of code, the Automated Teardown
mechanism deserves its own unit tests. Because it is now outside the Test Method,
we can write Self-Checking Tests (see page 26) for it! If we want to be really 
careful (some might say paranoid), we can use Delta Assertions (page 485) to 
verify that any objects that persist after the teardown operation really existed 
before the test was performed. 
Variation: Automated Exercise Teardown 
We can make the tests even more “self-cleaning” by also cleaning up the objects 
created by the SUT. This effort involves designing the SUT using an observable 
Object Factory (see Dependency Lookup on page 686) so that we can automati-
cally register any objects created by the SUT while it is being exercised. During 
the teardown phase we can delete these objects, too. 
Motivating Example 
In this example, we create several objects using Creation Methods and need to 
tear them down when the test in complete. To do so, we introduce a try/fi nally
block to ensure that our In-line Teardown (page 509) code executes even when 
the assertions fail. 
Automated Teardown
Automated 
Teardown