Hamcrest 测试集合
Contents
1. 简介
这篇文章说明了如何使用 Hamcrest 匹配器来处理和测试集合。
首先,让我们做一个快速的静态导入来涵盖我们接下来要使用的大部分实用 API:
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<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<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)));