Java Reference
In-Depth Information
The
JU
nit team did not invent software testing or even the unit test. Originally, the
term
unit test
described a test that examined the behavior of a single
unit of work
.
Over time, usage of the term
unit test
broadened. For example,
IEEE
has defined
unit testing as “Testing of individual hardware or software units
or groups of related
units
” (emphasis added).
4
In this topic, we use the term
unit test
in the narrower sense of a test that examines
a single unit in isolation from other units. We focus on the type of small, incremental
tests that programmers apply to their own code. Sometimes we call these
programmer
tests
to differentiate them from quality assurance tests or customer tests (
http://
Here's a generic description of a typical unit test from our perspective: “Confirm
that the method accepts the expected range of input and that the method returns the
expected value for each input.”
This description asks us to test the behavior of a method through its interface. If
we give it value
x
, will it return value
y
? If we give it value
z
instead, will it throw the
proper exception?
DEFINITION
A
unit test
examines the behavior of a distinct
unit of work
. Within
a Java application, the “distinct unit of work” is often (but not always) a single
method. By contrast,
integration tests
and
acceptance tests
examine how various
components interact. A
unit of work
is a task that isn't directly dependent on
the completion of any other task.
Unit tests often focus on testing whether a method follows the terms of its
API
contract
.
Like a written contract by people who agree to exchange certain goods or services
under specific conditions, an
API
contract is a formal agreement made by the signa-
ture of a method. A method requires its callers to provide specific object references or
primitive values and returns an object reference or primitive value. If the method
can't fulfill the contract, the test should throw an exception, and we say that the
method has broken its contract.
In this chapter, we walk through creating a unit test for a simple class from scratch.
We start by writing a test and its minimal runtime framework, so you can see how we
used to do things. Then we roll out
JU
nit to show you how the right tools can make life
much simpler.
DEFINITION
An
API
contract
is a view of an application programming interface
(
API
) as a formal agreement between the caller and the callee. Often the unit
tests help define the
API
contract by demonstrating the expected behavior.
The notion of an
API
contract stems from the practice of, popularized by the
Eiffel programming language (
http://archive.eiffel.com/doc/manuals/tech-
nology/contract).
4
EEE Standard Computer Dictionary: A Compilation of IEEE Standard Computer Glossaries
(New York, IEEE, 1990).