Java Reference
In-Depth Information
The
Hamcrest matchers
allow you to write more expressive tests, at the cost of an additional
download. Support for them is built into
JUnit
4 with the
assertThat
static method, but
you need to download the matchers from
Hamcrest
or via the Maven artifact.
Here's an example of using the Hamcrest Matchers:
public
public class
class
HamcrestDemo
HamcrestDemo
{
@Test
public
public
void
void
testNameConcat
() {
Person p
=
new
new
Person
(
"Ian"
,
"Darwin"
);
String f
=
p
.
getFullName
();
assertThat
(
f
,
containsString
(
"Ian"
));
assertThat
(
f
,
equalTo
(
"Ian Darwin"
));
assertThat
(
f
,
not
(
containsString
(
"/"
)));
// contrived, to show syntax
}
}
See Also
If you prefer flashier GUI output, several
JUnit
variants (built using Swing and AWT; see
Chapter 14
)
will run the tests with a GUI. More importantly, all modern IDEs provide built-
in support for running tests; in Eclipse, you can right-click a project in the Package Explorer
and select Run As→Unit Test to have it find and run all the
JUnit
tests in the entire project.
JUnit
offers considerable documentation of its own; download it from the website listed
earlier.
Also, for
manual testing
of graphical components, I have developed a simple component
tester, described in
Showing Graphical Components Without Writing Main
.
An alternative Unit Test framework for Java is
TestNG
; it got some early traction by adopt-
ing Java annotations before
JUnit
did, but since
JUnit
got with the annotations program,
JUnit
has remained the dominant package for Java Unit Testing.
Remember:
Test early and often!