
254
Chapter 16 Behavior Smells
watch the green bar grow as we run the tests. There may be notable pauses in the
execution; we may see explicit delays coded in a Test Method (page 348). If the
cause is not obvious, however, we can run different subsets (or subsuites) of tests
to see which ones run quickly and which ones take a long time to run.
A profi ling tool can come in handy to see where we are spending the extra
time in test execution. Of course, xUnit gives us a simple means to build our
own mini-profi ler: We can edit the setUp and tearDown methods of our Testcase
Superclass (page 638). We then write out the start/end times or test duration
into a log fi le, along with the name of the Testcase Class (page 373) and Test
Method. Finally, we import this fi le into a spreadsheet, sort by duration, and
voila—we have found the culprits. The tests with the longest execution times
are the ones on which it will be most worthwhile to focus our efforts.
Causes
The specifi c cause of the Slow Tests could lie either in how we built the SUT or
in how we coded the tests themselves. Sometimes, the way the SUT was built
forces us to write our tests in a way that makes them slow. This is particularly a
problem with legacy code or code that was built with a “test last” perspective.
Cause: Slow Component Usage
A component of the SUT has high latency.
Root Cause
The most common cause of Slow Tests is interacting with a database in many of
the tests. Tests that have to write to a database to set up the fi xture and read a
database to verify the outcome (a form of Back Door Manipulation; see page 327)
take about 50 times longer to run than the same tests that run against in-memory
data structures. This is an example of the more general problem of using slow
components.
Possible Solution
We can make our tests run much faster by replacing the slow components with
a Test Double (page 522) that provides near-instantaneous responses. When the
slow component is the database, the use of a Fake Database (see Fake Object)
can make the tests run on average 50 times faster! See the sidebar “Faster Tests
Without Shared Fixtures” on page 319 for other ways to skin this cat.
Slow Tests