
416
How It Works
As we write tests, we don’t bother asking whether a desired utility function
exists; we just use it! (It helps to pretend that we have a loyal helper sitting
next to us who will quickly fi ll in the bodies of any functions we call that do
not exist as yet.) We write our tests in terms of these magic functions with
Intent-Revealing Names [SBPP], passing as parameters only those things that
will be verifi ed in the assertions or that should affect the outcome of the test.
Once we’ve written the test in this very intent-revealing style, we must implement
all of the magic functions that we’ve been calling. The functions that create objects
are our Creation Methods; they encapsulate the complexity of object creation. The
simple ones call the appropriate constructor, passing it suitable default values for
anything needed but not supplied as a parameter. If any of the constructor argu-
ments are other objects, the Creation Method will fi rst create those depended-on
objects before calling the constructor.
The Creation Method may be placed in all the same places where we put
Test Utility Methods (page 599). As usual, the decision is based on the expected
scope of reuse and the Creation Method’s dependencies on the API of the SUT.
A related pattern is Object Mother (see Test Helper on page 643), which is a
combination of Creation Method, Test Helper, and optionally Automated Tear-
down (page 503).
When to Use It
We should use a Creation Method whenever constructing a Fresh Fixture
(page 311) requires signifi cant complexity and we value Tests as Documentation.
Another key indicator for using Creation Method is that we are building the
system in a highly incremental way and we expect the API of the system (and
especially the object constructors) to change frequently. Encapsulating knowl-
edge of how to create a fi xture object is a special case of SUT API Encapsulation
(see Test Utility Method), and it helps us avoid both Fragile Tests (page 239) and
Obscure Tests.
The main drawback of a Creation Method is that it creates another API for
test automaters to learn. This isn’t much of a problem for the initial test devel-
opers because they are typically involved in building this API but it can create
“one more thing” for new additions to the team to learn. Even so, this API
should be pretty easy to understand because it is just a set of Factory Methods
[GOF] organized in some way.
If we are using a Prebuilt Fixture (page 429), we should use Finder Methods
(see Test Utility Method) to locate the prebuilt objects. At the same time, we
Creation
Method
Chapter 20 Fixture Setup Patterns