
419
we want to reduce the likelihood that a change in the test execution order of
Chained Tests (page 454) will cause tests to fail. Mind you, the tests will run
more slowly because each test will call all the preceding tests it depends on each
time each test is run rather than each test being run only once per test run. Of
course, each test needs to call only the specifi c tests it actually depends on, not all
tests in the test suite. This slowdown won’t be very noticeable if we have replaced
any slow components, such as a database, with a Fake Object (page 551).
Wrapping the Test Method in a Creation Method is a better option than
calling the Test Method directly from the client Test Method because most Test
Methods are named based on which test condition(s) they verify, not what (fi x-
ture) they leave behind. The Creation Method lets us put a nice Intent-Revealing
Name between the client Test Method and the implementing Test Method. It
also solves the Lonely Test (see Erratic Test) problem because the other test is
run explicitly from within the calling test rather than just assuming that it was
already run. This scheme makes the test less fragile and easier to understand but
it won’t solve the Interacting Tests (see Erratic Test) problem: If the test we call
fails and leaves the test fi xture in a different state than we expected, our test will
likely fail as well, even if the functionality we are testing is still working.
Motivating Example
In the following example, the testPurchase test requires a Customer to fi ll the role of
the buyer. The fi rst and last names of the buyer have no bearing on the act of pur-
chasing, but are required parameters of the Customer constructor; we do care that
the Customer’s credit rating is good (“G”) and that he or she is currently active.
public void testPurchase_firstPurchase_ICC() {
Customer buyer =
new Customer(17, "FirstName", "LastName", "G","ACTIVE");
// ...
}
public void testPurchase_subsequentPurchase_ICC() {
Customer buyer =
new Customer(18, "FirstName", "LastName", "G","ACTIVE");
// ...
}
The use of constructors in tests can be problematic, especially when we are
building an application incrementally. Every change to the parameters of the
constructor will force us to revisit a lot of tests or jump through hoops to keep
the constructor signatures backward compatible for the sake of the tests.
Creation
Method
Creation Method