
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: July 29, 2020
This cookbook illustrates how to make use of Hamcrest matchers to work with and test collections.
The format of the cookbook is example focused and practical – no extraneous details and explanations necessary.
First, let’s do a quick static import to cover most of the utility APIs we’re going to use next:
import static org.hamcrest.Matchers.*;
check if single element is in a collection
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItem("cd"));
assertThat(collection, not(hasItem("zz")));
check if multiple elements are in a collection
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItems("cd", "ef"));
check all elements in a collection
– with strict order
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, contains("ab", "cd", "ef"));
– with any order
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, containsInAnyOrder("cd", "ab", "ef"));
check if collection is empty
List<String> collection = Lists.newArrayList();
assertThat(collection, empty());
check if array is empty
String[] array = new String[] { "ab" };
assertThat(array, not(emptyArray()));
check if Map is empty
Map<String, String> collection = Maps.newHashMap();
assertThat(collection, equalTo(Collections.EMPTY_MAP));
check if Iterable is empty
Iterable<String> collection = Lists.newArrayList();
assertThat(collection, emptyIterable());
check size of a collection
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasSize(3));
checking size of an iterable
Iterable<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, Matchers.<String> iterableWithSize(3));
check condition on every item
List<Integer> collection = Lists.newArrayList(15, 20, 25, 30);
assertThat(collection, everyItem(greaterThan(10)));
This format is an experiment – I’m publishing some of my internal development cookbooks on a given topic – Google Guava and now Hamcrest. The goal is to have this information readily available online – and to add to it whenever I run into a new useful example.