Fixture Teardown Patterns
Patterns in This Chapter
Teardown Strategy
Garbage-Collected Teardown 500
Automated Teardown 503
Code Organization
In-line Teardown 509
Implicit Teardown 516
Garbage-Collected Teardown
How do we tear down the Test Fixture?
We let the garbage collection mechanism provided by the programming language clean up after our test .
A large part of making tests repeatable and robust is ensuring that the test fixture is torn down after each test and a new one created for the next test run. This strategy is known as a Fresh Fixture (page 311 ). In languages that provide garbage collection , much of the teardown can happen automatically if we refer to resources via local and instance variables.
How It Works
Many of the objects created during the course of our test (including both fixture setup and exercising the SUT) are transient objects that are kept alive only as long as there is a reference to them somewhere in the program that created them. The garbage collection mechanisms of modern languages use various algorithms to detect "garbage." What is most important, though, is how they determine that something is not garbage: Any object that is reachable from any other live object or from global (i.e., static) variables will not be garbage collected.
When running our tests, the Test Automation Framework (page 298 ) creates a Testcase Object (page 382 ) for each Test Method (page 348 ) in our Testcase Class (page 373 ) and adds those objects to a Test Suite Object (page 387 ). Whenever a new test run is started, the framework typically throws away the existing test suite and builds a new one (to be sure everything is fresh). When the old test suite is discarded, any objects referenced only by instance variables in those tests become candidates for garbage collection.
When to Use It
We should use Garbage-Collected Teardown whenever we possibly can because it will save us a lot of effort!
If our programming takes place in an environment that doesn't support garbage collection, or if we have resources that aren't garbage collected automatically (e.g., files, sockets, records in a database), we'll need to destroy or free those resources explicitly. If we are using a Shared Fixture (page 317 ), we won't be able to use Garbage-Collected Teardown unless we do something fancy to hold the reference to the fixture in such a way that it will go out of scope when our test suite has finished running.
We can use In-line Teardown (page 509 ), Implicit Teardown (page 516 ), or Automated Teardown (page 503 ) to ensure that they are released properly.
Implementation Notes
Some members of the xUnit family and some IDEs go so far as to replace the classes each time the test suite is run. We may see this behavior show up as an option called "Reload Classes" or it may be forced upon us. We must be careful if we decide to take advantage of this feature to perform Garbage-Collected Teardown with fixture holding class variables , as our tests may stop running if we change IDEs or try running our tests from the command line (e.g., from "Cruise Control" or a build script.)
Motivating Example
The following test creates some in-memory objects during fixture setup and explicitly destroys them using In-line Teardown . (We could have used Implicit Teardown in this example but that just makes it harder for readers to see what is going on.)
public void testCancel_proposed_UIT() {
// fixture setup
Flight proposedFlight = createAnonymousProposedFlight();
// exercise SUT
proposedFlight.cancel();
// verify outcome
try{
assertEquals( FlightState.CANCELLED,
proposedFlight.getStatus());
} finally {
// teardown
proposedFlight.delete();
proposedFlight = null;
}
}
Because these objects are not persistent, the code to delete the proposedFlight is unnecessary and just makes the test more complicated and harder to understand.
Refactoring Notes
To convert to Garbage-Collected Teardown , we need only remove the unnecessary cleanup code. If we had been using a class variable to hold the reference to the object, we would have had to convert it to either an instance variable or a local variable, both of which would have moved us from a Shared Fixture to a Fresh Fixture .
Example: Garbage-Collected Teardown
In this reworked test, we let Garbage-Collected Teardown do the job for us.
public void testCancel_proposed_GCT() {
// fixture setup
Flight proposedFlight = createAnonymousProposedFlight();
// exercise SUT
proposedFlight.cancel();
// verify outcome
assertEquals( FlightState.CANCELLED,
proposedFlight.getStatus());
// teardown
// Garbage collected when proposedFlight goes out of scope
}
Note how much simpler the test has become!
Automated Teardown
Also known as
Test Object Registry
How do we tear down the Test Fixture?
We keep track of all resources that are created in a test and automatically destroy/free them during teardown .
A large part of making tests repeatable and robust is ensuring that the test fixture is torn down after each test and a new one created for the next test run. This strategy is known as a Fresh Fixture (page 311 ). Leftover objects and database records, as well as open files and connections, can at best cause performance degradations 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 scenario. 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 ).
A better solution is to let the test infrastructure track the objects created and clean them up auto-magically when the test is complete.
How It Works
The core of the solution is a mechanism to register each persistent item (i.e., object, record, connection, and so on) we create in the test. We maintain a list (or lists) of registered objects that need some action to be taken to destroy them. This can be as simple as tossing each object into a collection. At the end of the test, we traverse the collection and destroy each object. We will want to catch any errors that we encounter so that one object's cleanup error will not cause the rest of the cleanup to be aborted.
When to Use It
We can use Automated Teardown whenever we have persistent resources that need to be cleaned up to keep the test environment functioning. (This happens more often in customer tests than in unit tests.) This pattern addresses both Unrepeatable Tests (see Erratic Test on page 228 ) and Interacting Tests (see Erratic Test ) by keeping the objects created in one test from lingering into the execution of a subsequent test.
Automated Teardown isn't very difficult to build, and it will save us a large amount of grief and effort. Once we have built it for one project, we should be able to reuse the teardown logic on subsequent projects for very little effort.
Implementation Notes
Automated Teardown comes in two flavors. The basic flavor tears down only objects that were created as part of fixture setup. The more advanced version also destroys any objects that were created by the SUT while it was being exercised.
Variation: Automated Fixture Teardown
The simplest solution is to register the objects we create in our Creation Methods (page 415 ). Although this pattern will not tear down the objects created by the SUT, by dealing with our fixture it reduces the effort and likelihood of errors significantly.
There are two key challenges with this variation:
- Finding a generic way to clean up the registered objects
- Ensuring that our Automated Teardown code is run for each registered object
Given that the latter challenge is the easier problem, let us deal with it first. When we are tearing down a Persistent Fresh Fixture (see Fresh Fixture ), the 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 fixture 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 automatically 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/finally block to ensure that our In-line Teardown (page 509 ) code executes even when the assertions fail.
public void testGetFlightsByOrigin_NoInboundFlight_SMRTD()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
BigDecimal inboundAirport = null;
FlightDto expFlightDto = null;
try {
inboundAirport = createTestAirport("1IF");
expFlightDto = createTestFlight(outboundAirport, inboundAirport);
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(inboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
} finally {
try {
facade.removeFlight(expFlightDto.getFlightNumber());
} finally {
try {
facade.removeAirport(inboundAirport);
} finally {
facade.removeAirport(outboundAirport);
}
}
}
}
Note that we must use nested try/finally constructs within the finally block to ensure that any errors in the teardown don't keep us from finishing the job.
Refactoring Notes
Introducing Automated Teardown involves two steps. First, we add the Automated Teardown mechanism to our Testcase Class . Second, we remove any In-line Teardown code from our tests.
Automated Teardown can be implemented on a specific Testcase Class or it can be inherited (or mixed in) via a generic class. Either way, we need to make sure we register all of our newly created objects so that the mechanism knows to delete them when the test is finished. This is most easily done inside Creation Methods that already exist. Alternatively, we can use an Extract Method [Fowler] refactoring to move the direct constructor calls into newly created Creation Methods and add the registration.
The generic Automated Teardown mechanism should be invoked from the tearDown method. Although this can be done on our own Testcase Class, it is almost always better to put this method on a Testcase Superclass that all our Testcase Classes inherit from. If we don't already have a Testcase Superclass, we can easily create one by doing an Extract Class [Fowler] refactoring and then doing a Pull Up Method [Fowler] refactoring on any methods (and fields) associated with the Automated Teardown mechanism.
Example: Automated Teardown
There is not much to see in this refactored test because all of the teardown code has been removed.
public void testGetFlightsByOriginAirport_OneOutboundFlight()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
BigDecimal inboundAirport = createTestAirport("1IF");
FlightDto expectedFlightDto =
createTestFlight( outboundAirport, inboundAirport);
// Exercise System
List flightsAtOrigin =
facade.getFlightsByOriginAirport(outboundAirport);
// Verify Outcome
assertOnly1FlightInDtoList( "Flights at origin",
expectedFlightDto,
flightsAtOrigin);
}
Here is where all the work gets done! The Creation Method has been modified to register the object it just created.
private List allAirportIds;
private List allFlights;
protected void setUp() throws Exception {
allAirportIds = new ArrayList();
allFlights = new ArrayList();
}
private BigDecimal createTestAirport(String airportName)
throws FlightBookingException {
BigDecimal newAirportId = facade.createAirport(
airportName, " Airport" + airportName,
"City" + airportName);
allAirportIds.add(newAirportId);
return newAirportId;
}
Next comes the actual Automated Teardown logic. In this example, it lives on our Testcase Class and is called from the tearDown method. To keep this example very simple, this logic has been written specifically to handle airports and flights. More typically, it would live in the Testcase Superclass , where it could be used by all Testcase Classes, and would use a generic object destruction mechanism so that it would not have to care what types of objects it was deleting.
protected void tearDown() throws Exception {
removeObjects(allAirportIds, "Airport");
removeObjects(allFlights, "Flight");
}
public void removeObjects(List objectsToDelete, String type) {
Iterator i = objectsToDelete.iterator();
while (i.hasNext()) {
try {
BigDecimal id = (BigDecimal) i.next();
if ("Airport"==type) {
facade.removeAirport(id);
} else {
facade.removeFlight(id);
}
} catch (Exception e) {
// do nothing if the remove failed
}
}
}
If we were tearing down a Shared Fixture , we would annotate our tearDown method with the suitable annotation or attribute (e.g., @afterClass or [TestFixtureTearDown] ) or move it to a Setup Decorator .
Example: Automated Exercise Teardown
If we wanted to take the next step and automatically tear down any objects created within the SUT, we could modify the SUT to use an observable Object Factory. In our test, we would add the following code:
ResourceTracker tracker;
public void setUp() {
tracker = new ResourceTracker();
ObjectFactory.addObserver(tracker);
}
public void tearDown() {
tracker.cleanup();
ObjectFactory.removeObserver(tracker);
}
This last example assumes that the Automated Teardown logic has been moved into the cleanup method on the ResourceTracker .
In-line Teardown
How do we tear down the Test Fixture?
We include teardown logic at the end of the Test Method immediately after the result verification .
A large part of making tests repeatable and robust is ensuring that the test fixture is torn down after each test and a new one created for the next test run. This strategy is known as a Fresh Fixture (page 311 ). Leftover objects and database records, as well as open files and connections, can at best cause performance degradations 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.
At a minimum, we should write In-line Teardown code that cleans up resources left over after our test.
How It Works
As we write a test, we mentally keep track of all objects the test creates that will not be cleaned up automatically. After writing the code to exercise the SUT and verify the outcome, we add logic to the end of the Test Method (page 348 ) to destroy any objects that will not be cleaned up automatically by the garbage collector. We use the relevant language feature to ensure that the teardown code is run regardless of the outcome of the test.
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 fixture 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 benefit 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 benefit, indeed. It is almost always better to strive for Automated Teardown (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 fixture.
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 consideration 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 regardless of how the first block terminates. In Java, this construct takes the form of a try block with an associated finally block.
Variation: Teardown Guard Clause
To protect against a failure caused by trying to tear down a resource that doesn't exist, we can put a "guard clause" around the logic. Its inclusion reduces the likelihood of a test error caused by the teardown logic.
Variation: Delegated Teardown
We can move much of the teardown logic out of the Test Method by calling a Test Utility Method (page 599 ). Although this strategy reduces the amount of teardown logic cluttering the test, we still need to place an error-handling construct around at least the assertions and the exercising of the SUT to ensure that it gets called. Using Implicit Teardown is almost always a better solution.
Variation: Naive In-line Teardown
Naive In-line Teardown is what we have when we forget to put the equivalent of a try/finally block around our test logic to ensure that our teardown logic always executes. It leads to Resource Leakage (see Erratic Test ), which in turn may lead to Erratic Tests .
Motivating Example
The following test creates a persistent object ( airport ) as part of the fixture. Because the object is stored in a database, it is not subject to Garbage-Collected Teardown and must be explicitly destroyed. If we do not include teardown logic in the test, each time the test is run it will create another object in the database. This may lead to Unrepeatable Tests unless the test uses Distinct Generated Values (see Generated Value on page 723 ) to ensure that the created objects do not violate any unique key constraints.
public void testGetFlightsByOriginAirport_NoFlights_ntd()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(outboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
}
Example: Naive In-line Teardown
In this naive solution to this problem, we added a line after the assertion to destroy the airport created in the fixture setup.
public void testGetFlightsByOriginAirport_NoFlights()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(outboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
facade.removeAirport(outboundAirport);
}
Unfortunately, this solution isn't really adequate because the teardown logic won't be exercised if the SUT encounters an error or if the assertions fail. We could try moving the fixture cleanup before the assertions but this still wouldn't address the issue with errors occurring inside the SUT. Clearly, we need a more general solution.
Refactoring Notes
We need either to place an error-handling construct around the exercising of the SUT and the assertions or to move the teardown code into the tearDown method. Either way, we need to ensure that all the teardown code runs, even if some parts of it fail. This usually involves the judicious use of try/finally control structures around each step of the teardown process.
Example: In-line Teardown
In this Java example, we have introduced a try/finally block around the exercise SUT and result verification phases of the test to ensure that our teardown code is run.
public void testGetFlightsByOriginAirport_NoFlights_td()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
try {
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(outboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
} finally {
facade.removeAirport(outboundAirport);
}
}
Now the exercising of the SUT and the assertions both appear in the try block and the teardown logic is found in the finally block. This separation is crucial to making In-line Teardown work properly. We should not include a catch block unless we are writing an Expected Exception Test (see Test Method ).
Example: Teardown Guard Clause
Here, we've added a Teardown Guard Clause to the teardown code to ensure it isn't run if the airport doesn't exist:
public void testGetFlightsByOriginAirport_NoFlights_TDGC()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
try {
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(outboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
} finally {
if (outboundAirport!=null) {
facade.removeAirport(outboundAirport);
}
}
}
Example: Multiresource In-line Teardown (Java)
If multiple resources need to be cleaned up in the same test, we must ensure that all the teardown code runs even if some of the teardown statements contain errors. This goal can be accomplished by nesting each subsequent teardown step inside another block of guaranteed code, as in this Java example:
public void testGetFlightsByOrigin_NoInboundFlight_SMRTD()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
BigDecimal inboundAirport = null;
FlightDto expFlightDto = null;
try {
inboundAirport = createTestAirport("1IF");
expFlightDto = createTestFlight(outboundAirport, inboundAirport);
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(inboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
} finally {
try {
facade.removeFlight(expFlightDto.getFlightNumber());
} finally {
try {
facade.removeAirport(inboundAirport);
} finally {
facade.removeAirport(outboundAirport);
}
}
}
}
This scheme gets very messy in a hurry if we must clean up more than a few resources. In such a situation, it makes more sense to organize the resources into an array or list and then to iterate over that array or list. At that point we are halfway to implementing Automated Teardown .
Example: Delegated Teardown
We can also delegate the teardown from within the Test Method if we don't believe we can come up with a completely generic way cleanup strategy that will work for all tests.
public void testGetFlightsByOrigin_NoInboundFlight_DTD()
throws Exception {
// Fixture Setup
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 {
teardownFlightAndAirports( outboundAirport,
inboundAirport,
expectedFlightDto);
}
}
private void teardownFlightAndAirports(
BigDecimal firstAirport,
BigDecimal secondAirport,
FlightDto flightDto)
throws FlightBookingException {
try {
facade.removeFlight( flightDto.getFlightNumber() );
} finally {
try {
facade.removeAirport(secondAirport);
} finally {
facade.removeAirport(firstAirport);
}
}
}
The optimizers among us will notice that the two flight numbers are actually available as attributes of the flightDto . The paranoid will counter that because the teardownFlightAndAirports method could be called before the flightDto is constructed, we cannot count on using it to access the Airports . Hence we must pass the Airports in individually. The need to think this way is why a generic Automated Teardown is so attractive; it avoids having to think at all!
Implicit Teardown
Also known as
Hooked Teardown, Framework-Invoked Teardown, Teardown Method
How do we tear down the Test Fixture?
The Test Automation Framework calls our cleanup logic in the tearDown method after every Test Method .
A large part of making tests repeatable and robust is ensuring that the test fixture is torn down after each test and a new one created for the next test run. This strategy is known as a Fresh Fixture (page 311 ). Leftover objects and database records, as well as open files and connections, can at best cause performance degradations and at worst cause tests to fail or systems to crash.
When we can't take advantage of Garbage-Collected Teardown (page 500 ) and we have several tests with the same objects to tear down, we can put the teardown logic into a special tearDown method that the Test Automation Framework (page 298 ) calls after each Test Method (page 348 ) is run.
How It Works
Anything that needs to be cleaned up can be freed or destroyed in the final phase of the Four-Phase Test (page 358 )—namely, the fixture teardown phase. Most members of the xUnit family of Test Automation Frameworks support the concept of Implicit Teardown , wherein they call the tearDown method of each Testcase Object (page 382 ) after the Test Method has been run.
The tearDown method is called regardless of whether the test passes or fails. This scheme ensures that we have the opportunity to clean up, undisturbed by any failed assertions. Be aware, however, that many members of the xUnit family do not call tearDown if the setUp method raises an error.
When to Use It
We can use Implicit Teardown whenever several tests with the same resources need to be destroyed or freed explicitly after the test has been completed and those resources will not be destroyed or freed automatically. We may discover this requirement 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.
If the objects created by the test are internal resources and subject to automated memory management, then Garbage-Collected Teardown may eliminate a lot of work for us. If each test has a completely different set of objects to tear down, then In-line Teardown (page 509 ) may be more appropriate. In many cases, we can completely avoid manually written teardown logic by using Automated Teardown (page 503 ).
Implementation Notes
The teardown logic in the tearDown method is most often created by refactoring from tests that had In-line Teardown . The tearDown method may need to be "flexible" or "accommodating" for several reasons:
- When a test fails or when a test error occurs, the Test Method may not have created all the fixture objects.
- If all the Test Methods in the Testcase Class (page 373 ) don't use identical fixtures, 1 there may be different sets of objects to clean up for different tests.
Variation: Teardown Guard Clause
We can avoid arbitrarily Conditional Test Logic (page 200 ) if we deal with the case where only a subset of the objects to be torn down are actually present by putting a guard clause (a simple if statement) around each teardown operation to guard against the resource not being present. With this technique, a suitably coded tearDown method can tear down various fixture configurations. Contrast this with the setUp method, which can set up only the lowest common denominator fixture for the Test Methods that share it.
Motivating Example
The following test creates several standard objects during fixture setup. Because the objects are persisted in a database, they must be cleaned up explicitly after every test. Each test (only one of several is shown here) contains the same in-line teardown logic to delete the objects.
public void testGetFlightsByOrigin_NoInboundFlight_SMRTD()
throws Exception {
// Fixture Setup
BigDecimal outboundAirport = createTestAirport("1OF");
BigDecimal inboundAirport = null;
FlightDto expFlightDto = null;
try {
inboundAirport = createTestAirport("1IF");
expFlightDto = createTestFlight(outboundAirport, inboundAirport);
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(inboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
} finally {
try {
facade.removeFlight(expFlightDto.getFlightNumber());
} finally {
try {
facade.removeAirport(inboundAirport);
} finally {
facade.removeAirport(outboundAirport);
}
}
}
}
There is enough Test Code Duplication (page 213 ) here to warrant converting these tests to Implicit Teardown .
Refactoring Notes
First, we find the most representative example of teardown in all the tests. Next, we do an Extract Method [Fowler] refactoring on that code and call the resulting method tearDown . Finally, we delete the teardown logic in each of the other tests. We may need to introduce Teardown Guard Clauses around any teardown logic that may not be needed in every test. We should also surround each teardown attempt with a try/finally block to ensure that the remaining teardown logic executes even if an earlier attempt fails.
Example: Implicit Teardown
This example shows the same tests with the teardown logic removed to the tearDown method. Note how much smaller the tests have become.
BigDecimal outboundAirport;
BigDecimal inboundAirport;
FlightDto expFlightDto;
public void testGetFlightsByAirport_NoInboundFlights_NIT()
throws Exception {
// Fixture Setup
outboundAirport = createTestAirport("1OF");
inboundAirport = createTestAirport("1IF");
expFlightDto = createTestFlight( outboundAirport, inboundAirport);
// Exercise System
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(inboundAirport);
// Verify Outcome
assertEquals(0,flightsAtDestination1.size());
}
protected void tearDown() throws Exception {
try {
facade.removeFlight( expFlightDto.getFlightNumber() );
} finally {
try {
facade.removeAirport(inboundAirport);
} finally {
facade.removeAirport(outboundAirport);
}
}
}
Note that there is no try/finally block around the exercising of the SUT and the assertions. This structure helps the test reader understand that this is not an Expected Exception Test (see Test Method ). Also, we didn't need to put a Guard Clause [SBPP] in front of each operation because the try/finally block ensures that a failure is noncatastrophic; thus there is no real harm in trying to perform the operation. We did have to convert our fixture holding local variables into instance variables to allow the tearDown method to access the fixture.