Hamcrest Collections Cookbook

1. Introduction

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.*;

2. The Cookbook

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"));

Check all elements in a collection – 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)));

3. Conclusion

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.

The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven-based project, so it should be easy to import and run as it is.

Related posts:

Hướng dẫn Java Design Pattern – Facade
Java – InputStream to Reader
Java Program to Implement Double Order Traversal of a Binary Tree
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Java Program to Check Multiplicability of Two Matrices
Java Program to Implement LinkedHashMap API
Đồng bộ hóa các luồng trong Java
The Modulo Operator in Java
Interface trong Java 8 – Default method và Static method
Java Program to Perform Partition of an Integer in All Possible Ways
Java Program to Implement Treap
Spring Boot - Zuul Proxy Server and Routing
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Count Occurrences of a Char in a String
Lập trình đa luồng trong Java (Java Multi-threading)
Testing an OAuth Secured API with Spring MVC
How to Return 404 with Spring WebFlux
Java Map With Case-Insensitive Keys
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Hướng dẫn Java Design Pattern – Proxy
Java Program to Check Cycle in a Graph using Topological Sort
Database Migrations with Flyway
Hướng dẫn sử dụng lớp Console trong java
Java – Generate Random String
Spring Boot - Tomcat Port Number
Queue và PriorityQueue trong Java
HttpClient Connection Management
Quick Guide on Loading Initial Data with Spring Boot
Spring Boot - Rest Controller Unit Test
Java Program to Implement PriorityQueue API
Java Program to Implement Hash Tables with Quadratic Probing
Câu lệnh điều khiển vòng lặp trong Java (break, continue)