Java Reference
In-Depth Information
ing how an object should behave (what is referred to as its
contract
). The unit tests en-
sure that the expected behavior occurs (they do this by verifying the result of a method
and using the different
JUnit.Assert
methods).
The first step to writing a unit test is to create a new class that describes the behavi-
or you want to verify. One of the general unit-test naming conventions is to create a
class with the same name as the class being tested with the postfix of
Test
; in this re-
cipe's example, the main class is called
Recipe11_2_MathAdder
, while the testing
class is called
Recipe11_2_MathAdderTest
.
The unit test class (
MathAdderTest
) will contain methods that check and verify
the behavior of the class. To do so, method names are annotated.
Annotations
are forms
of metadata, and a developer can “annotate” specified portions of code, thereby adding
information to the annotated code. This extra information is not used by the program,
but by the compiler/builder (or external tools) to guide the compilation, building, and/
or testing of the code. For unit-testing purposes, you annotate the methods that are part
of the unit test by specifying
@Test
before each method name. Within each method,
you use
Assert.assertEquals
(or any of the other
Assert
static methods) to
verify behavior.
The
Assert.assertEquals
method instructs the unit-testing framework to
verify that the expected value of the method call from the class that you are testing is
the same as the actual value returned by its method call. In the recipe example,
Assert.assertEquals
verifies that the
MathAdder
is correctly adding the two
integers. While the scope of this class is trivial, it shows the bare minimum require-
ments to have a fully functional unit test.
If the
Assert
call succeeds, it gets reported in the unit test framework as a
“passed” test; if the
Assert
call fails, then the unit test framework will stop and dis-
play a message showing where the unit test failed. Most modern IDEs have the capabil-
ity of running unit test classes by simply right-clicking the name and selecting Run/De-
bug (and that's the intended way of running the
Chapter_11_2_MathAdderTest
recipe).
While it is true that IDEs can run unit tests while developing, they are created with
the intention of being run automatically (usually triggered by a scheduled build or by a
version control system's check-in), which is what the Recipe 11-3 talks about.
11-3. Scripting Your Unit Tests
Problem