
436
When to Use It
We can use Lazy Setup whenever we need to create a Shared Fixture yet still
want to be able to run each test by itself. We can also use Lazy Setup instead
of other techniques such as Setup Decorator (page 447) and Suite Fixture Set-
up (page 441) if it is not crucial that the fi xture be torn down. For example,
we could use Lazy Setup when we are using a fi xture that can be torn down by
Garbage-Collected Teardown (page 500). We might also use Lazy Setup when
we are using Distinct Generated Values (see Generated Value on page 723) for
all database keys and aren’t worried about leaving extra records lying around
after each test; Delta Assertions (page 485) make this approach possible.
The major disadvantage of Lazy Setup is the fact that while it is easy to
discover that we are running the fi rst test and need to construct the fi xture,
it is diffi cult to determine that we are running the last test and the fi xture
should be destroyed. Most members of the xUnit family of Test Automation
Frameworks (page 298) do not provide any way to determine this fact other
than by using a Setup Decorator for the entire test suite. A few members of the
xUnit family support Suite Fixture Setup (NUnit, VbUnit, and JUnit 4.0 and
newer, to name a few), which provides setUp/tearDown “bookends” for a Testcase
Class (page 373). Unfortunately, this ability won’t help us if we are writing our
tests in Ruby, Python, or PLSQL!
Some IDEs and Test Runners (page 377) automatically reload our classes every
time the test suite is run. This causes the original class variable to go out of scope,
and the fi xture will be garbage-collected before the new version of the class is run.
In these cases there may be no negative consequence of using Lazy Setup.
A Prebuilt Fixture (page 429) is another alternative to setting up the Shared
Fixture for each test run. Its use can lead to Unrepeatable Tests (see Erratic
Test) if the fi xture is corrupted by some of the tests.
Implementation Notes
Because Lazy Setup makes sense only with Shared Fixtures, Lazy Setup carries
all the same baggage that comes with Shared Fixtures.
Normally, Lazy Setup is used to build a Shared Fixture to be used by a single
Testcase Class. The reference to the fi xture is held in a class variable. Things
get a bit trickier if we want to share the fi xture across several Testcase Classes.
We could move both the Lazy Initialization logic and the class variable to a
Testcase Superclass (page 638) but only if our language supports inheritance of
class variables. The other alternative is to move the logic and variables to a Test
Helper (page 643).
Lazy Setup
Chapter 20 Fixture Setup Patterns