
Class–Instance Duality
Back in high school physics, we learned about the “wave–particle duality”
of light. Sometimes light acts like a particle (e.g., going through a small
aperture), and sometimes it acts like a wave (e.g., rainbows). The behavior
of Testcase Classes (page 373) sometimes reminds me of this concept. Let
me explain why.
Developers new to xUnit often ask, “Why is the class we subclass called
TestCase when we have several Test Methods on it? Shouldn’t it be called
TestSuite?” These questions make a lot of sense when we are focused
primarily on the view of the class when we are writing the test code as
opposed to when we are running the code.
When we are writing test code, we concentrate on the Test Methods. The
Testcase Class is primarily just a place to put the methods. About the only
time we think of objects is when we use Implicit Setup (page 424) and
need to create fi elds (instance variables) to hold them between the invo-
cation of the setUp method and when they are used in the Test Method.
When developers new to xUnit test automation are writing their fi rst tests,
they tend to code by example. Following an existing example is a good
way to get something working quickly but it doesn’t necessarily help the
developer understand what is really going on.
At runtime, the xUnit framework typically creates one instance of the
Testcase Class for each Test Method. The Testcase Class acts as a Test
Suite Factory (see Test Enumeration on page 399) that builds a Test Suite
Object (page 387) containing all the instances of itself, one instance for
each Test Method. Now, it’s not very often that a static method on a class
returns an instance of another class containing many instances of itself.
If this behavior wasn’t odd enough, the fact that xUnit reports the test
failures using the Test Method name can be enough to obscure from many
test automaters the existence of “objects inside.”
When we examine the object relationships at runtime, things become a bit
clearer. The Test Suite Object returned by the Test Suite Factory contains
one or more Testcase Objects (page 382). So far, so good. Each of these
objects is an instance of our Testcase Class. Each instance is confi gured
to run one of the Test Methods. More importantly, each will run a differ-
ent Test Method. (How this happens is described in more detail in Test
Discovery on page 393.) So each instance of our Testcase Class is, indeed,
a test case. The Test Methods are just how we tell each instance what it
should test.
Testcase
Class
Chapter 19 xUnit Basics Patterns
374