
110
Chapter 10 Result Verification
Using Built-in Assertions
We use the assertions provided by our testing framework to specify what should
be and depend on them to tell us when it isn’t so! But simply using the built-in
assertions is only a small part of the story.
The simplest form of result verifi cation is the assertion in which we specify
what should be true. Most members of the xUnit family support a range of dif-
ferent Assertion Methods, including the following:
• Stated Outcome Assertions (see Assertion Method) such as assertTrue
(aBooleanExpression)
• Simple Equality Assertions such as assertEquals(expected, actual)
• Fuzzy Equality Assertions such as assertEquals(expected, actual, tolerance),
which are used for comparing fl oats
Of course, the test programming language has some infl uence on the nature of
the assertions. In JUnit, SUnit, CppUnit, NUnit, and CsUnit, most of the Equal-
ity Assertions take a pair of Objects as their parameters. Some languages support
“overloading” of method parameter types so we can have different implemen-
tations of an assertion for different types of objects. Some languages—C, for
example—don’t support objects, so we cannot compare objects, only values.
There are several issues to consider when using Assertion Methods. Naturally,
the fi rst priority is the verifi cation of all things that should be true. The better
our assertions, the fi ner our Safety Net (see page 24) and the higher our confi -
dence in our code. The second priority is the documentation value of the asser-
tions. Each test should make it very clear that “When the system is in state S1
and I do X, the result should be R and the system should be in state S2.” We
put the system into state S1 in our fi xture setup logic. “I do X” corresponds to
the exercise SUT phase of the test. “The result is R” and “the system is in state
S2” are implemented using assertions. Thus we want to write our assertions in
such a way that they succinctly describe “R” and “S2.”
Another thing to consider is that when the test fails, we want the failure
message to tell us enough to enable us to identify the problem.
2
Therefore, we
should almost always include an Assertion Message (page 370) as the optional
message parameter (assuming our xUnit family member has one!). This tactic
avoids the possibility of us playing Assertion Roulette (page 224), in which we
cannot even tell which assertion is failing without running the test interactively;
2
In his book [TDD-APG], Dave Astels claims he never/rarely used the Eclipse Debugger
while writing the code samples because the assertions always told him enough about
what was wrong. This is what we strive for!