
We create an instance of the SUT and call the method(s) that we want to test. We
then assert that the expected outcome has occurred. In other words, we follow
the normal steps of a Four-Phase Test. What we don’t do is catch any exceptions
that could happen. Instead, we let the Test Automation Framework (page 298)
catch and report them. Doing otherwise would result in Obscure Tests (page 186)
and would mislead the test reader by making it appear as if exceptions were
expected. See Tests as Documentation for the rationale behind this approach.
Another benefi t of avoiding try/catch-style code is that when errors do occur,
it is a lot easier to track them down because the Test Automation Framework
reports the location where the actual error occurred deep in the SUT rather
than the place in our test where we called an Assertion Method (page 362) such
as fail or assertTrue. These kinds of errors turn out to be much easier to trouble-
shoot than assertion failures.
Variation: Expected Exception Test
Writing software that passes the Simple Success Test is pretty straightforward.
Most of the defects in software appear in the various alternative paths—especially
the ones that relate to error scenarios, because these scenarios are often Untested
Requirements (see Production Bugs on page 268) or Untested Code (see Produc-
tion Bugs). An Expected Exception Test helps us verify that the error scenarios
have been coded correctly. We set up the test fi xture and exercise the SUT in
each way that should result in an error. We ensure that the expected error has
occurred by using whatever language construct we have available to catch the
error. If the error is raised, fl ow will pass to the error-handling block. This diver-
sion may be enough to let the test pass, but if the type or message contents of the
exception or error is important (such as when the error message will be shown
to a user), we can use an Equality Assertion (see Assertion Method) to verify it.
If the error is not raised, we call fail to report that the SUT failed to raise an
error as expected.
We should write an Expected Exception Test for each kind of exception that
the SUT is expected to raise. It may raise the error because the client (i.e., our
test) has asked it to do something invalid, or it may translate or pass through an
error raised by some other component it uses. We should not write an Expected
Exception Test for exceptions that the SUT might raise but that we cannot force
to occur on cue, because these kinds of errors should show up as test failures
in the Simple Success Tests. If we want to verify that these kinds of errors are
handled properly, we must fi nd a way to force them to occur. The most common
way to do so is to use a Test Stub (page 529) to control the indirect input of the
SUT and raise the appropriate errors in the Test Stub.
Test Method
Chapter 19 xUnit Basics Patterns
350