Hamcrest Collections Cookbook – 哈姆克雷斯特收藏的食谱

最后修改: 2013年 10月 29日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

This cookbook illustrates how to make use of Hamcrest matchers to work with and test collections.

本手册说明了如何利用Hamcrest匹配器来处理和测试集合

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:

首先,让我们做一个快速的静态导入,以涵盖我们接下来要使用的大部分实用API。

import static org.hamcrest.Matchers.*;

2. The Cookbook

2.食谱

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是否为空

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

3.结论

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.

这种格式是一种尝试–我正在发布一些关于特定主题的内部开发食谱–Google Guava和现在的Hamcrest。我们的目标是让这些信息可以随时在线获取–并且每当我遇到一个新的有用的例子时,就会对它进行补充。

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.

所有这些例子和代码片段的实现都可以在GitHub上找到–这是一个基于Maven的项目,所以应该很容易导入并按原样运行。