Hamcrest collections arrays

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

3.結論

這種格式是一種實驗-我正在發布有關給定主題的一些內部開髮指南-Google Guava和現在的Hamcrest。我們的目標是使這些信息可以隨時在線獲得,並在我遇到一個新的有用示例時加以添加。

所有這些示例和代碼段的實現都**可以在GitHub上找到**-這是一個基於Maven的項目,因此應該很容易直接導入和運行。

0 條評論,你可以發表評論,我們會進行改進
Comment author placeholder