1. 简介
本文档展示如何使用Hamcrest匹配器处理和测试集合。手册采用示例驱动、注重实践的编写方式——省略不必要的细节和解释。
首先,快速导入后续用到的核心工具类:
import static org.hamcrest.Matchers.*;
2. 操作手册
检查集合是否包含单个元素
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItem("cd"));
assertThat(collection, not(hasItem("zz")));
检查集合是否包含多个元素
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItems("cd", "ef"));
检查集合所有元素
✅ 严格顺序匹配
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, contains("ab", "cd", "ef"));
✅ 任意顺序匹配
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, containsInAnyOrder("cd", "ab", "ef"));
检查集合是否为空
List<String> collection = Lists.newArrayList();
assertThat(collection, empty());
检查数组是否为空
String[] array = new String[] { "ab" };
assertThat(array, not(emptyArray()));
检查Map是否为空
Map<String, String> collection = Maps.newHashMap();
assertThat(collection, equalTo(Collections.EMPTY_MAP));
检查Iterable是否为空
Iterable<String> collection = Lists.newArrayList();
assertThat(collection, emptyIterable());
检查集合大小
List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasSize(3));
检查Iterable大小
Iterable<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, Matchers.<String> iterableWithSize(3));
检查所有元素满足条件
List<Integer> collection = Lists.newArrayList(15, 20, 25, 30);
assertThat(collection, everyItem(greaterThan(10)));
3. 总结
本文档是系列技术手册的实验性尝试——继Google Guava集合手册后,现发布Hamcrest集合操作指南。目标是将这些实用技巧在线共享,并在遇到新用例时持续更新。
所有示例代码的完整实现**可在GitHub仓库**获取——基于Maven构建,可直接导入运行。