
Why Does a Fixture Persist?
The fi xture we construct may hang around after the Test Method (page 348)
has fi nished executing for one of two reasons. First, if the fi xture primarily
consists of the state of some other objects or components on which the SUT
depends, its persistence is determined by whether those other objects are them-
selves persistent. A database is one such beast. That’s because as soon as some
code persists the fi xture objects into a database, the objects “hang around”
long after our test is done. Their existence in the database opens the door
to collisions between multiple runs of our own test (Unrepeatable Test; see
Erratic Test). Other tests may also be able to access those objects, which can
result in other forms of Erratic Tests such as Interacting Tests and Test Run
Wars. If we must use a database or other form of object persistence, we should
take extra steps to keep the fi xture private. In addition, we should tear down
the fi xture after each Test Method.
The second reason that a fi xture might persist lies within the control of our
tests—namely, which kind of variable we choose to hold the reference to the
fi xture. Local variables naturally go out of scope when the Test Method fi nishes
executing; therefore any fi xture held in a local variable will be destroyed by
garbage collection. Instance variables go out of scope when the Testcase Object
is destroyed
8
and require explicit teardown only if the xUnit framework doesn’t
recreate the Testcase Objects during each test run. By contrast, class variables
usually result in persistent fi xtures that can outlive a single test method or even
a test run and should therefore be avoided when using a Fresh Fixture.
In practice, our fi xture will not normally be persistent in unit tests
9
unless
we have tightly coupled our application logic to the database. A fi xture is more
likely to be persistent when we are writing customer tests or possibly compo-
nent tests.
Fresh Fixture Setup
Construction of the fi xture is largely unaffected by whether it is persistent or tran-
sient. The primary consideration is the location of the code to set up the fi xture. We
can use In-line Setup (page 408) if the fi xture setup is relatively simple. For more
complex fi xtures, we generally prefer using Delegated Setup (page 411) when our
8
Most members of the xUnit family create a separate Testcase Object (page 382) for
each Test Method. A few do not, however. This difference can trip up unwary test
automaters when they fi rst start using these members of the family because instance
variables may unexpectedly act like class variables. For a detailed description of this
issue, see the sidebar “There’s Always an Exception” (page 384).
9
The sidebar “Unit Test Rulz” (page 307) explains what constitutes a unit test.
Fresh Fixture
Fresh
Fixture
313