Java Reference
In-Depth Information
B
@Before
public void setUpList() {
values = new ArrayList<String>();
values.add("x");
values.add("y");
values.add("z");
}
@Test
public void testWithoutHamcrest() {
assertTrue(values.contains("one")
|| values.contains("two")
|| values.contains("three"));
}
}
What we do in this example is construct a simple JU nit test, exactly like the ones we've
been constructing so far. We have a @Before fixture B , which will initialize some data
for our test, and then we have a single test method C . In this test method you can see
that we make a long and hard-to-read assertion D (maybe it's not that hard to read,
but it's definitely not obvious what it does at first glance). Our goal is to simplify the
assertion we make in the test method.
To solve this problem we're going to present a library of matchers for building test
expressions. Hamcrest ( http://code.google.com/p/hamcrest/) is a library that con-
tains a lot of helpful matcher objects (known also as constraints or predicates), ported
in several languages (Java, C++, Objective-C, Python, and PHP ). Note that Hamcrest
isn't a testing framework itself, but rather it helps you declaratively specify simple
matching rules. These matching rules can be used in many different situations, but
they're particularly helpful for unit testing.
Listing 3.18 is the same test method, this time written using the Hamcrest library.
C
D
Listing 3.18
Hamcrest library to simplify our assert declarations
[...]
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.JUnitMatchers.hasItem;
[...]
B
@Test
public void testWithHamcrest() {
assertThat(values, hasItem(anyOf(equalTo("one"), equalTo("two"),
equalTo("three"))));
}
[...]
Here we reuse listing 3.17 and add another test method to it. This time we import
the needed matchers and the assertThat method B , and after that we construct a
test method. In the test method we use one of the most powerful features of the
matchers—they can nest within each other C . Whether you prefer assertion code
C
 
 
 
Search WWH ::




Custom Search