
384
Chapter 19 xUnit Basics Patterns
There’s Always an Exception
Whether we are learning to conjugate verbs in a new language or looking
for patterns in how software is built, there’s always an exception!
One of the most notable exceptions in the xUnit family relates to
the use of a Testcase Object (page 382) to represent each Test Meth-
od (page 348) at runtime. This key design feature of xUnit offers a
way to achieve an Independent Test (see page 42). The only members
of the xUnit family that don’t follow this scheme are TestNG and
NUnit (version 2.x). For the reasons described below, the builders
of NUnit 2.0 chose to stray from the well-worn path of one Testcase
Object per Test Method and create only a single instance of the Test-
case Class (page 373). This instance, which they call the test fi xture, is
then reused for each Test Method. One of the authors of NUnit 2.0,
James Newkirk, writes:
I think one of the biggest screw-ups that was made when we wrote
NUnit V2.0 was to not create a new instance of the test fi xture class
for each contained test method. I say “we” but I think this one was
my fault. I did not quite understand the reasoning in JUnit for cre-
ating a new instance of the test fi xture for each test method. I look
back now and see that reusing the instance for each test method
allows someone to store a member variable from one test and use
it in another. This can introduce execution-order dependencies,
which for this type of testing is an anti-pattern. It is much better to
fully isolate each test method from the others. This requires that a
new object be created for each test method.
Unfortunately, this has some very interesting—and undesirable—
consequences when one is familiar with the “JUnit New Instance Behav-
ior” of a separate Testcase Object per method. Because the object is reused,
any objects it refers to via an instance variable are available to all subse-
quent tests. This results in an implicit Shared Fixture (page 317) along
with all the forms of Erratic Tests (page 228) that go with it. James goes
on to say:
Since it would be diffi cult to change the way that NUnit works now,
and too many people would complain, I now make all of the mem-
ber variables in test fi xture classes static. It’s almost like truth in
advertising. The result is that there is only one instance of this
variable, no matter how many test fi xture objects are created. If
the variable is static, then someone who may not be familiar with
Testcase
Object