Java Reference
In-Depth Information
the
Calculator
object. After that, at
F
we assert the correctness of the result of the
Calculator
's
squareRoot()
method with all of the test data.
If you run this example, you'll get a result like what you'd see if you'd just run five
distinct assertions like the following:
assertEquals( 1, calculator.squareRoot ( 1 ) );
assertEquals( 2, calculator.squareRoot ( 4 ) );
assertEquals( 3, calculator.squareRoot ( 9 ) );
assertEquals( 4, calculator.squareRoot ( 16 ) );
assertEquals( 5, calculator.squareRoot ( 25 ) );
A.5
New assertions and assumptions
This final section deals with the new assertion and assumption mechanisms intro-
duced in
JU
nit 4.x. It also reveals the integration between
JU
nit and the Hamcrest
matcher—something that allows you to write useful match statements to simplify
your assertions.
A.5.1
Hamcrest assertions
In version 4.4 of
JU
nit, the Hamcrest assertion mechanism was incorporated. The
Hamcrest assertion mechanism was introduced in
JM
ock and provides a new, robust,
fluent
API
for assertions. With Hamcrest assertions, you're able to write more readable
and flexible test assertions like these in listing A.11.
Listing A.11
Hamcrest assertions in JUnit 4.4+
[...]
import
org.junit.Test;
import
static
org.junit.Assert.*;
import
static
org.hamcrest.CoreMatchers.is;
import
static
org.hamcrest.CoreMatchers.not;
public
class
CalculatorTest {
@Test
public
void
squareRoot() {
Calculator c =
new
Calculator();
assertThat(2, is(c.squareRoot(4)));
assertThat(3, is(not(c.squareRoot(4))));
}
}
The
org.hamcrest.CoreMatchers
and
org.junit.matchers.JUnitMatchers
pack-
ages are distributed with
JU
nit and contain numerous matchers. The Hamcrest match-
ers that come with
JU
nit are the first third-party classes included in
JU
nit.
If you find them insufficient, you can always get the full Hamcrest project from the
internet and use any of those matchers with
JU
nit.