日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Hamcrest Matchers教程

發布時間:2023/12/3 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Hamcrest Matchers教程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文是我們名為“ 用Mockito進行測試 ”的學院課程的一部分。

在本課程中,您將深入了解Mockito的魔力。 您將了解有關“模擬”,“間諜”和“部分模擬”的信息,以及它們相應的Stubbing行為。 您還將看到使用測試雙打和對象匹配器進行驗證的過程。 最后,討論了使用Mockito的測試驅動開發(TDD),以了解該庫如何適合TDD的概念。 在這里查看 !

在本教程中,我們將研究Hamcrest Matcher庫以及如何將其與JUnit和Mockito集成。

目錄

1.什么是Hamcrest? 2.包括Hamcrest 3.認識匹配者
3.1。 簡單匹配器 3.2。 簡單匹配器結合其他匹配器
4。結論

1.什么是Hamcrest?

Hamcrest是用于創建匹配對象的框架。 這些匹配器對象是謂詞,用于編寫在某些條件下可以滿足的規則。 它們通常用于自動化測試中,盡管它們可以用于其他情況下,例如數據驗證。 Hamcrest讓我們超越了簡單的JUnit斷言,并使我們能夠編寫非常具體,可讀的驗證代碼。

Hamcrest旨在使測試更具可讀性。 它充分利用靜態方法來創建斷言語法,該語法易于編寫和理解。 當與JUnit和Mockito結合使用時,它使我們能夠編寫清晰,簡潔的測試,以滿足“測試一件事”的良好單元測試的特性。

假設我們有一個String,我們想測試它是否與另一個期望的字符串相等,我們可以使用JUnit斷言來測試它:

assertEquals(expected, actual);

在Hamcrest中,我們使用JUnit assertThat(valueUnderTest, matcher)方法。 此方法始終構成Hamcrest斷言的基礎; 我們斷言被測值滿足匹配謂詞。 要在最基本的水平上用hamcrest重寫上述測試,我們可以編寫:

assertThat(actual, equalTo(expected));

注意assertThat約定將要測試的實際值作為第一個參數,這與assertEquals約定相反。 這是對可讀性的改進,但是Hamcrest還以is()匹配器的形式為我們提供了一些不錯的語法糖。 該匹配器本身不執行任何操作,它只是中繼其輸入匹配器的結果,從而使您的斷言代碼可以像英語一樣讀取。 讓我們使用is()重寫上面的內容:

assertThat(actual, is(equalTo(expected)));

很好,很可讀!

Hamcrest的匹配器失敗時,它會生成詳細的輸出,并指定期望值和實際值,以幫助您確定測試失敗的原因。 查看以下測試用例:

@Testpublic void test_failed() throws Exception {// GivenInteger number = 7;// ThenassertThat(number, greaterThan(10));}

顯然,該測試將失敗,但是Hamcrest將提供有關失敗的詳細信息:

java.lang.AssertionError: Expected: a value greater than <10>but: <7> was less than <10>

在本教程中,我們將遵循僅在一個單元測試中包含一個斷言的約定。 這似乎是重復的,尤其是在許多測試中測試的設置部分相同的情況下,但是這是單元測試中的良好做法。 它使我們能夠創建針對性的測試-僅當單個斷言失敗時,測試才會失敗,其他所有斷言將繼續執行。 它使我們能夠創建可讀的測試-我們可以一目了然地看到測試的目的。 它使我們能夠創建記錄代碼的測試-我們可以使用表達測試目的的測試名稱,從而傳達測試的詳細目的(請考慮customer_should_have_balance_updated_by_input_order_amount()而不是verifyOrderMethod() )。 它使我們能夠創建不易碎的測試-如果測試做得太多,則如果更改了不相關的功能,它可能會中斷,從而迫使我們重寫測試只是為了使其再次運行而無需更改實際的被測代碼。

如果我們遵循“測試一件事”的習慣,那么將來我們將編寫出更好的單元測試!

2.包括Hamcrest

如果使用的是Maven,則可以將Hamcrest添加到您的項目中,并且對pom.xml具有以下依賴性

<dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-all</artifactId><version>1.3</version></dependency>

如果您使用的是Gradle,請添加以下內容

dependencies {testCompile "org.hamcrest:hamcrest-all:1.3"}

要將hamcrest直接添加到項目的類路徑中,可以從https://code.google.com/p/hamcrest/下載hamcrest-all-1.3.jar到硬盤上的某個位置。

右鍵單擊您的eclipse項目,然后選擇“屬性”,然后在左窗格中選擇“ Java Build Path”,然后在右側選擇“ Libraries”。

在“庫”選項卡上,單擊“添加外部罐子”按鈕,然后導航到先前下載的所有hamcrest罐子。 選擇罐子,它現在已添加到您的項目中并可供使用。

請注意,JUnit與簡化版本的Hamcrest(Hamcrest Core)捆綁在一起,因此,如果JUnit出現在類路徑上的Hamcrest之前,則編譯器將選擇該版本。 為了解決這個問題,請確保Hamcrest在類路徑上的JUnit之前出現。 您可以在Maven中通過在所有其他依賴項之前列出hamcrest-all依賴項來實現此目的。

與Mockito靜態方法一樣,我們可以通過啟動Window-> Preferences并將Hamcrest庫添加到Eclipse內容輔助中,并轉到左側導航欄中的Java / Editor / Content Assist / Favorites。 之后,按照圖1添加以下內容作為“ New Type…”

  • org.hamcrest.Matchers

啟動Window-> Preferences,然后轉到左側導航欄中的Java / Editor / Content Assist / Favorites。 之后,按照圖1添加以下內容作為“ New Type…”

圖1 – Content Assist收藏夾

3.認識匹配者

Hamcrest提供了一個靜態工廠方法庫,用于在org.hamcrest.Matchers類中創建Matchers,因此您可以通過靜態導入引入所有Matchers

import static org.hamcrest.Matchers.*

但是,如果這樣做,則存在命名沖突的風險,因為Hamcrest和Mockito都提供了靜態的any()方法,因此建議導入您單獨使用的每個靜態方法。
現在,我們將在Hamcrest Matchers庫中查看所有可用的Matchers。 它們將分為兩大類: 用于測試值的匹配器(簡單),和用于組合其他匹配器(聚合)的匹配器。

簡單匹配器

以下匹配器主要用于測試輸入值。

3.1.1。 任何()

匹配給定類型的任何變量。

@Testpublic void test_any() throws Exception {// GivenString myString = "hello";// ThenassertThat(myString, is(any(String.class))); }

3.1.2。 任何東西()

匹配任何東西。

@Testpublic void test_anything() throws Exception {// GivenString myString = "hello";Integer four = 4;// ThenassertThat(myString, is(anything()));assertThat(four, is(anything()));}

3.1.3。 arrayContaining()

數組的各種匹配器,數組的長度必須匹配匹配器的數量,并且它們的順序很重要。

數組是否按輸入到匹配器的順序包含所有給定項目?

@Testpublic void test_arrayContaining_items() throws Exception {// GivenString[] strings = {"why", "hello", "there"};// ThenassertThat(strings, is(arrayContaining("why", "hello", "there")));}

數組中是否包含按順序匹配匹配器輸入列表的項目?

@Testpublic void test_arrayContaining_list_of_matchers() throws Exception {// GivenString[] strings = {"why", "hello", "there"};// Thenjava.util.List<org.hamcrest.Matcher<? super String>> itemMatchers = new ArrayList<>();itemMatchers.add(equalTo("why"));itemMatchers.add(equalTo("hello"));itemMatchers.add(endsWith("here"));assertThat(strings, is(arrayContaining(itemMatchers)));}

數組是否按順序包含與輸入vararg匹配器匹配的項目?

@Testpublic void test_arrayContaining_matchers() throws Exception {// GivenString[] strings = {"why", "hello", "there"};// ThenassertThat(strings, is(arrayContaining(startsWith("wh"), equalTo("hello"), endsWith("here"))));}

3.1.4。 arrayContainingInAnyOrder()

數組的各種匹配器,數組的長度必須匹配匹配器的數量,但是它們的順序并不重要。

數組是否包含所有給定項?

@Testpublic void test_arrayContainingInAnyOrder_items() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenassertThat(strings, is(arrayContainingInAnyOrder("hello", "there", "why")));}

數組中是否包含與Matchers的輸入集合匹配的項目?

@Testpublic void test_arrayContainingInAnyOrder_collection_of_matchers() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenSet<org.hamcrest.Matcher<? super String>> itemMatchers = new HashSet<>();itemMatchers.add(equalTo("hello"));itemMatchers.add(equalTo("why"));itemMatchers.add(endsWith("here"));assertThat(strings, is(arrayContainingInAnyOrder(itemMatchers)));}

數組是否包含與輸入vararg匹配器匹配的項目?

@Testpublic void test_arrayContainingInAnyOrder_matchers() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenassertThat(strings, is(arrayContainingInAnyOrder(endsWith("lo"), startsWith("the"), equalTo("why"))));}

3.1.5。 arrayWithSize()

各種匹配器,用于檢查數組是否具有特定長度。

輸入數組是否具有指定的長度?

@Testpublic void test_arrayWithSize_exact() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenassertThat(strings, is(arrayWithSize(3)));}

輸入數組的長度是否與指定的匹配項匹配?

@Testpublic void test_arrayWithSize_matcher() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenassertThat(strings, is(arrayWithSize(greaterThan(2))));}

3.1.6。 相近()

可以與Double或BigDecimal一起使用的匹配器,以檢查某個值是否在期望值的指定誤差范圍內。

@Testpublic void test_closeTo_double() throws Exception {// GivenDouble testValue = 6.3;// ThenassertThat(testValue, is(closeTo(6, 0.5)));}

大十進制

@Testpublic void test_closeTo_bigDecimal() throws Exception {// GivenBigDecimal testValue = new BigDecimal(324.0);// ThenassertThat(testValue, is(closeTo(new BigDecimal(350), new BigDecimal(50))));}

3.1.7。 comparesEqualTo()

創建一個Comparable匹配器,嘗試使用輸入值的compareTo()方法匹配輸入匹配器值。 如果compareTo()方法為輸入的匹配器值返回0,則匹配器將匹配,否則將不匹配。

@Testpublic void test_comparesEqualTo() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, comparesEqualTo("value"));}

3.1.8。 contains()

各種匹配器,可用于檢查輸入Iterable是否包含值。 值的順序很重要,并且Iterable中的項目數必須與要測試的值數相匹配。

輸入列表是否按順序包含所有值?

@Testpublic void test_contains_items() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenassertThat(strings, contains("why", "hello", "there"));}

輸入列表中是否包含按順序匹配輸入匹配器列表中所有匹配器的項目?

@Testpublic void test_contains_list_of_matchers() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenList<org.hamcrest.Matcher<? super String>> matchers = new ArrayList<>();matchers.add(startsWith("wh"));matchers.add(endsWith("lo"));matchers.add(equalTo("there"));assertThat(strings, contains(matchers));}

輸入列表中是否僅包含與輸入匹配項匹配的一項?

@Testpublic void test_contains_single_matcher() throws Exception {// GivenList<String> strings = Arrays.asList("hello");// ThenassertThat(strings, contains(startsWith("he")));}

輸入列表中是否包含按順序匹配輸入vararg匹配器中所有匹配器的項?

@Testpublic void test_contains_matchers() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenassertThat(strings, contains(startsWith("why"), endsWith("llo"), equalTo("there")));}

3.1.9。 containsInAnyOrder()

各種匹配器,可用于檢查輸入Iterable是否包含值。 值的順序并不重要,但是Iterable中的項目數必須與要測試的值數相匹配。

輸入列表是否以任何順序包含所有值?

@Testpublic void test_containsInAnyOrder_items() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenassertThat(strings, containsInAnyOrder("hello", "there", "why"));}

輸入列表中是否包含與輸入匹配器列表中的所有匹配器按任何順序匹配的項目?

@Testpublic void test_containsInAnyOrder_list_of_matchers() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenList<org.hamcrest.Matcher<? super String>> matchers = new ArrayList<>();matchers.add(equalTo("there"));matchers.add(startsWith("wh"));matchers.add(endsWith("lo")); assertThat(strings, containsInAnyOrder(matchers));}

輸入列表中是否包含以任何順序匹配輸入vararg匹配器中所有匹配器的項目?

@Testpublic void test_containsInAnyOrder_matchers() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenassertThat(strings, containsInAnyOrder(endsWith("llo"), equalTo("there"), startsWith("why")));}

3.1.10。 containsString()

如果被測字符串包含給定的子字符串,則匹配的匹配器。

@Testpublic void test_containsString() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, containsString("alu"));}

3.1.11。 空()

如果輸入Collections isEmpty()方法返回true,則匹配的匹配器。

@Testpublic void test_empty() throws Exception {// GivenSet<String> testCollection = new HashSet<>();// ThenassertThat(testCollection, is(empty()));}

3.1.12。 emptyArray()

如果輸入數組的長度為0,則匹配的匹配器。

@Testpublic void test_emptyArray() throws Exception {// GivenString[] testArray = new String[0];// ThenassertThat(testArray, is(emptyArray()));}

3.1.13。 emptyCollectionOf()

類型安全匹配器,如果輸入集合為給定類型且為空,則匹配。

@Testpublic void test_emptyCollectionOf() throws Exception {// GivenSet<String> testCollection = new HashSet<>();// ThenassertThat(testCollection, is(emptyCollectionOf(String.class)));}

3.1.14。 emptyIterable()

如果輸入Iterable沒有值,則匹配的匹配器。

@Testpublic void test_emptyIterable() throws Exception {// GivenSet<String> testCollection = new HashSet<>();// ThenassertThat(testCollection, is(emptyIterable()));}

3.1.15。 emptyIterableOf()

Typesafe Matcher,如果輸入的Iterable沒有值并且是給定類型,則匹配。

@Testpublic void test_emptyIterableOf() throws Exception {// GivenSet<String> testCollection = new HashSet<>();// ThenassertThat(testCollection, is(emptyIterableOf(String.class)));}

3.1.16。 以。。結束()

如果輸入String以給定的子字符串結尾,則匹配的匹配器。

@Testpublic void test_endsWith() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, endsWith("lue"));}

3.1.17。 等于()

如果輸入值在邏輯上等于給定測試值,則匹配的匹配器。 也可以在數組上使用,在這種情況下,它將檢查數組的長度并確保輸入測試數組中的所有值在邏輯上都等于指定數組的值。

單值。

@Testpublic void test_equalTo_value() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, equalTo("value"));}

數組。

@Testpublic void test_equalTo_array() throws Exception {// GivenString[] testValues = { "why", "hello", "there" };// ThenString[] specifiedValues = { "why", "hello", "there" };assertThat(testValues, equalTo(specifiedValues));}

3.1.18。 equalToIgnoringCase()

如果輸入的String值等于指定的String且忽略大小寫,則匹配的匹配器。

@Testpublic void test_equalToIgnoringCase() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, equalToIgnoringCase("VaLuE"));}

3.1.19。 equalToIgnoringWhiteSpace()

如果輸入的String值等于指定的String而不匹配多余的空格,則匹配該匹配器。 忽略所有前導和尾隨空格,并將所有剩余空格折疊為單個空格。

@Testpublic void test_equalToIgnoringWhiteSpace() throws Exception {// GivenString testValue = "this is my value ";// ThenassertThat(testValue, equalToIgnoringWhiteSpace("this is my value"));}

3.1.20。 eventFrom()

如果輸入EventObject來自給定Source,則匹配的Matcher。 也可以接受指定子類型的EventObeject 。

@Testpublic void test_eventFrom() throws Exception {// GivenObject source = new Object();EventObject testEvent = new EventObject(source);// ThenassertThat(testEvent, is(eventFrom(source)));}

指定子類型。

@Testpublic void test_eventFrom_type() throws Exception {// GivenObject source = new Object();EventObject testEvent = new MenuEvent(source);// ThenassertThat(testEvent, is(eventFrom(MenuEvent.class, source)));}

3.1.21。 比...更棒()

如果輸入測試值大于指定值,則匹配的匹配器。

@Testpublic void test_greaterThan() throws Exception {// GivenInteger testValue = 5;// ThenassertThat(testValue, is(greaterThan(3)));}

3.1.22。 GreaterThanOrEqual()

如果輸入測試值大于或等于指定值,則匹配的匹配器。

@Testpublic void test_greaterThanOrEqualTo() throws Exception {// GivenInteger testValue = 3;// ThenassertThat(testValue, is(greaterThanOrEqualTo(3)));}

3.1.23。 hasEntry()

如果給定映射包含與指定鍵和值匹配的條目,則匹配的匹配器或匹配器。

實際值

@Testpublic void test_hasEntry() throws Exception {// GivenInteger testKey = 1;String testValue = "one";Map<Integer, String> testMap = new HashMap<>();testMap.put(testKey, testValue);// ThenassertThat(testMap, hasEntry(1, "one"));}

匹配器

@Testpublic void test_hasEntry_matchers() throws Exception {// GivenInteger testKey = 2;String testValue = "two";Map<Integer, String> testMap = new HashMap<>();testMap.put(testKey, testValue);// ThenassertThat(testMap, hasEntry(greaterThan(1), endsWith("o")));}

3.1.24。 hasItem()

如果輸入Iterable具有至少一個與指定值或匹配器匹配的項目,則匹配的匹配器。

實際價值

@Testpublic void test_hasItem() throws Exception {// GivenList<Integer> testList = Arrays.asList(1,2,7,5,4,8);// ThenassertThat(testList, hasItem(4));}

匹配器

@Testpublic void test_hasItem_matcher() throws Exception {// GivenList<Integer> testList = Arrays.asList(1,2,7,5,4,8);// ThenassertThat(testList, hasItem(is(greaterThan(6))));}

3.1.25。 hasItemInArray()

如果輸入數組具有至少一個與指定值或匹配器匹配的項目,則匹配的匹配器。

實際價值

@Testpublic void test_hasItemInArray() throws Exception {// GivenInteger[] test = {1,2,7,5,4,8};// ThenassertThat(test, hasItemInArray(4));}

匹配器

@Testpublic void test_hasItemInArray_matcher() throws Exception {// GivenInteger[] test = {1,2,7,5,4,8};// ThenassertThat(test, hasItemInArray(is(greaterThan(6))));}

3.1.26。 hasItems()

如果輸入Iterable具有任意順序的所有指定值或匹配器,則匹配的匹配器。

實際值

public void test_hasItems() throws Exception {// GivenList<Integer> testList = Arrays.asList(1,2,7,5,4,8);// ThenassertThat(testList, hasItems(4, 2, 5));}

匹配器

@Testpublic void test_hasItems_matcher() throws Exception {// GivenList<Integer> testList = Arrays.asList(1,2,7,5,4,8);// ThenassertThat(testList, hasItems(greaterThan(6), lessThan(2)));}

3.1.27。 hasKey()

如果輸入Map具有至少一個與指定值或匹配器匹配的鍵,則匹配器匹配。

實際價值

@Testpublic void test_hasKey() throws Exception {// GivenMap<String, String> testMap = new HashMap<>();testMap.put("hello", "there");testMap.put("how", "are you?");// ThenassertThat(testMap, hasKey("hello"));}

匹配器

@Testpublic void test_hasKey_matcher() throws Exception {// GivenMap<String, String> testMap = new HashMap<>();testMap.put("hello", "there");testMap.put("how", "are you?");// ThenassertThat(testMap, hasKey(startsWith("h")));}

3.1.28。 hasProperty()

如果輸入的Object滿足Bean Convention并具有指定名稱的屬性,并且該屬性的值可選地與指定的Matcher匹配,則匹配該Matcher。

物業名稱

@Testpublic void test_hasProperty() throws Exception {// GivenJTextField testBean = new JTextField();testBean.setText("Hello, World!");// ThenassertThat(testBean, hasProperty("text"));}

屬性名稱和值匹配器

@Testpublic void test_hasProperty_value() throws Exception {// GivenJTextField testBean = new JTextField();testBean.setText("Hello, World!");// ThenassertThat(testBean, hasProperty("text", startsWith("H")));}

3.1.29。 hasSize()

如果輸入Collection具有指定的大小,或者它的大小與指定的匹配器匹配,則匹配器。
實際價值

@Testpublic void test_hasSize() throws Exception {// GivenList<Integer> testList = Arrays.asList(1,2,3,4,5);// ThenassertThat(testList, hasSize(5));}

匹配器

@Testpublic void test_hasSize_matcher() throws Exception {// GivenList<Integer> testList = Arrays.asList(1,2,3,4,5);// ThenassertThat(testList, hasSize(lessThan(10)));}

3.1.30。 hasToString()

如果輸入對象的toString()方法匹配指定的String或輸入匹配器,則匹配的匹配器。

正常價值

@Testpublic void test_hasToString() throws Exception {// GivenInteger testValue = 4;// ThenassertThat(testValue, hasToString("4"));}

匹配器

@Testpublic void test_hasToString_matcher() throws Exception {// GivenDouble testValue = 3.14;// ThenassertThat(testValue, hasToString(containsString(".")));}

3.1.31。 hasValue()

如果輸入Map具有至少一個與指定值或匹配器匹配的值,則匹配的匹配器。

實際價值

@Testpublic void test_hasValue() throws Exception {// GivenMap<String, String> testMap = new HashMap<>();testMap.put("hello", "there");testMap.put("how", "are you?");// ThenassertThat(testMap, hasValue("there"));}

匹配器

@Testpublic void test_hasValue_matcher() throws Exception {// GivenMap<String, String> testMap = new HashMap<>();testMap.put("hello", "there");testMap.put("how", "are you?");// ThenassertThat(testMap, hasValue(containsString("?")));}

3.1.32。 hasXPath()

如果輸入XML DOM節點滿足輸入XPath表達式,則匹配的匹配器。

節點是否包含與輸入XPath表達式匹配的節點?

@Testpublic void test_hasXPath() throws Exception {// GivenDocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();Node testNode = docBuilder.parse(new InputSource(new StringReader("<xml><top><middle><bottom>value</bottom></middle></top></xml>"))).getDocumentElement();// ThenassertThat(testNode, hasXPath("/xml/top/middle/bottom"));}

Node是否包含與輸入XPath表達式匹配的Node,并且該Node的值是否與指定的匹配器匹配?

@Testpublic void test_hasXPath_matcher() throws Exception {// GivenDocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();Node testNode = docBuilder.parse(new InputSource(new StringReader("<xml><top><middle><bottom>value</bottom></middle></top></xml>"))).getDocumentElement();// ThenassertThat(testNode, hasXPath("/xml/top/middle/bottom", startsWith("val")));}

節點是否在指定的名稱空間中包含與輸入XPath表達式匹配的節點?

@Test public void test_hasXPath_namespace() throws Exception {// GivenDocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();docFactory.setNamespaceAware(true);DocumentBuilder docBuilder = docFactory.newDocumentBuilder();Node testNode = docBuilder.parse(new InputSource(new StringReader("<xml xmlns:prefix='http://namespace-uri'><top><middle><prefix:bottom>value</prefix:bottom></middle></top></xml>"))).getDocumentElement();NamespaceContext namespace = new NamespaceContext() {public String getNamespaceURI(String prefix) {return "http://namespace-uri";}public String getPrefix(String namespaceURI) {return null;}public Iterator<String> getPrefixes(String namespaceURI) {return null;}};// ThenassertThat(testNode, hasXPath("//prefix:bottom", namespace)); }

Node是否在指定的名稱空間中包含一個與輸入XPath表達式匹配的Node,并且該Node的值是否與指定的Matcher匹配?

@Test public void test_hasXPath_namespace_matcher() throws Exception {// GivenDocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();docFactory.setNamespaceAware(true);DocumentBuilder docBuilder = docFactory.newDocumentBuilder();Node testNode = docBuilder.parse(new InputSource(new StringReader("<xml xmlns:prefix='http://namespace-uri'><top><middle><prefix:bottom>value</prefix:bottom></middle></top></xml>"))).getDocumentElement();NamespaceContext namespace = new NamespaceContext() {public String getNamespaceURI(String prefix) {return "http://namespace-uri";}public String getPrefix(String namespaceURI) {return null;}public Iterator<String> getPrefixes(String namespaceURI) {return null;}};// ThenassertThat(testNode, hasXPath("//prefix:bottom", namespace, startsWith("val"))); }

3.1.33。 instanceOf()

如果輸入對象是給定類型,則匹配器。

@Test public void test_instanceOf() throws Exception {// GivenObject string = "Hello, World!";// ThenassertThat(string, instanceOf(String.class)); }

3.1.34。 isEmptyOrNullString()

當輸入字符串為空或null時匹配的匹配器。

@Test public void test_isEmptyOrNullString() throws Exception {// GivenString emptyString = ";String nullString = null;// ThenassertThat(emptyString, isEmptyOrNullString());assertThat(nullString, isEmptyOrNullString()); }

3.1.35。 isEmptyString()

當輸入字符串為空時匹配的匹配器。

@Test public void test_isEmptyString() throws Exception {// GivenString emptyString = ";// ThenassertThat(emptyString, isEmptyString()); }

3.1.36。 isIn()

當在給定的Collection或Array中找到輸入項時匹配的匹配器。

@Test public void test_isIn() throws Exception {// GivenSet<Integer> set = new HashSet<>();set.add(3);set.add(6);set.add(4);// ThenassertThat(4, isIn(set)); }

3.1.37。 是其中之一()

當輸入對象是給定對象之一時匹配的匹配器。

@Test public void test_isOneOf() throws Exception {// ThenassertThat(4, isOneOf(3,4,5)); }

3.1.38。 iterableWithSize()

當輸入Iterable具有指定大小時匹配或與指定大小匹配器匹配的匹配器。

實際價值

@Test public void test_iterableWithSize() throws Exception {// GivenSet<Integer> set = new HashSet<>();set.add(3);set.add(6);set.add(4);// ThenassertThat(set, iterableWithSize(3)); }

匹配器

@Test public void test_iterableWithSize_matcher() throws Exception {// GivenSet<Integer> set = new HashSet<>();set.add(3);set.add(6);set.add(4);// ThenassertThat(set, iterableWithSize(lessThan(4))); }

3.1.39。 少于()

匹配器,使用compareTo方法匹配輸入對象小于指定值的可比較對象。

@Test public void test_lessThan() throws Exception {// ThenassertThat("apple", lessThan("zoo")); }

3.1.40。 lessThanOrEqualTo()

匹配器,使用compareTo方法匹配輸入對象小于或等于指定值的可比較對象。

@Test public void test_lessThanOrEqualTo() throws Exception {// ThenassertThat(2, lessThanOrEqualTo(2)); }

3.1.41。 不()

包裹現有匹配器并反轉其匹配邏輯的匹配器

@Test public void test_not_matcher() throws Exception {// ThenassertThat("zoo", not(lessThan("apple"))); }

當與值而不是匹配器一起使用時,也是not(equalTo(...))的別名

@Test public void test_not_value() throws Exception {// ThenassertThat("apple", not("orange")); }

3.1.42。 notNullValue()

當輸入值不為null時匹配的匹配器。

@Test public void test_notNullValue() throws Exception {// ThenassertThat("apple", notNullValue()); }

3.1.43。 nullValue()

當輸入值為null時匹配的匹配器。

@Test public void test_nullValue() throws Exception {// GivenObject nothing = null;// ThenassertThat(nothing, nullValue()); }

3.1.44。 sameInstance()

當輸入對象與指定值相同的實例時匹配的匹配器。

@Test public void test_sameInstance() throws Exception {// GivenObject one = new Object();Object two = one;// ThenassertThat(one, sameInstance(two)); }

3.1.45。 samePropertyValuesAs()

當輸入Bean具有與指定Bean相同的屬性值時匹配的匹配項,即,如果被測Bean上具有屬性,則它們必須存在,并且具有與在測試條件中指定的Bean相同的值。

給定以下Java類:

public class Bean {private Integer number;private String text;public Integer getNumber() {return number;}public void setNumber(Integer number) {this.number = number;}public String getText() {return text;}public void setText(String text) {this.text = text;} }

我們可以編寫以下測試:

@Testpublic void test_samePropertyValuesAs() throws Exception {// GivenBean one = new Bean();one.setText("text");one.setNumber(3);Bean two = new Bean();two.setText("text");two.setNumber(3);// ThenassertThat(one, samePropertyValuesAs(two));}

3.1.46。 以。。開始()

如果輸入字符串以給定前綴開頭的匹配項。

@Testpublic void test_startsWith() throws Exception {// GivenString test = "Beginnings are important!";// ThenassertThat(test, startsWith("Beginning"));}

3.1.47。 stringContainsInOrder()

如果輸入String包含給定Iterable中的子字符串,則按從Iterable返回的順序進行匹配的Matcher。

@Testpublic void test_stringContainsInOrder() throws Exception {// GivenString test = "Rule number one: two's company, but three's a crowd!";// ThenassertThat(test, stringContainsInOrder(Arrays.asList("one", "two", "three")));}

3.1.48。 theInstance()

當輸入對象與指定值相同的實例時匹配的匹配器。 行為與“ sameInstance()”相同

@Test public void test_theInstance() throws Exception {// GivenObject one = new Object();Object two = one;// ThenassertThat(one, theInstance(two)); }

3.1.49。 typeCompatibleWith()

當輸入類型的對象可以分配給指定基本類型的引用時匹配的匹配器。

@Testpublic void test_typeCompatibleWith() throws Exception {// GivenInteger integer = 3;// ThenassertThat(integer.getClass(), typeCompatibleWith(Number.class));}

簡單匹配器結合其他匹配器

以下匹配器主要用于組合其他匹配器。

3.2.1。 所有的()

當所有輸入Matchers都匹配時匹配的Matcher的行為類似于邏輯AND。 可以使用單個Matchers或Iterable Matchers。

個人匹配器

@Testpublic void test_allOf_individual() throws Exception {// GivenString test = "starting off well, gives content meaning, in the end";// ThenassertThat(test, allOf(startsWith("start"), containsString("content"), endsWith("end")));}

匹配器的迭代

@Testpublic void test_allOf_iterable() throws Exception {// GivenString test = "Hello, world!";List<Matcher<? super String>> matchers = Arrays.asList(containsString("world"), startsWith("Hello"));// ThenassertThat(test, allOf(matchers));}

3.2.2。 任何()

當任何輸入匹配器匹配時匹配的匹配器,其行為類似于邏輯或。 可以使用單個Matchers或Iterable Matchers。

個人匹配器

@Testpublic void test_anyOf_individual() throws Exception {// GivenString test = "Some things are present, some things are not!";// ThenassertThat(test, anyOf(containsString("present"), containsString("missing")));}

匹配器的迭代

@Testpublic void test_anyOf_iterable() throws Exception {// GivenString test = "Hello, world!";List<Matcher<? super String>> matchers = Arrays.asList(containsString("Hello"), containsString("Earth"));// ThenassertThat(test, anyOf(matchers));}

3.2.3。 array()

當輸入數組的元素分別使用指定的Matchers依次進行匹配時匹配的Matcher。 匹配器的數量必須等于數組的大小。

@Testpublic void test_array() throws Exception {// GivenString[] test = {"To be", "or not to be", "that is the question!"};// ThenassertThat(test, array(startsWith("To"), containsString("not"), instanceOf(String.class)));}

3.2.4。 都()

匹配器,當與它的可組合匹配器.and()結合使用時,將在兩個指定匹配器匹配時匹配。

@Testpublic void test_both() throws Exception {// GivenString test = "Hello, world!";// ThenassertThat(test, both(startsWith("Hello")).and(endsWith("world!")));}

3.2.5。 要么()

匹配器,當與它的可組合匹配器.or()結合使用時,如果指定的匹配器匹配,則匹配器。

@Testpublic void test_either() throws Exception {// GivenString test = "Hello, world!";// ThenassertThat(test, either(startsWith("Hello")).or(endsWith("universe!")));}

3.2.6。 is()

當輸入匹配器匹配時匹配的匹配器,只是為了方便起見,使斷言更像英語。

@Testpublic void test_is_matcher() throws Exception {// GivenInteger test = 5;// ThenassertThat(test, is(greaterThan(3)));}

也用作is(equalTo(...))的別名,類似于not(...)和not(equalTo(...))

@Testpublic void test_is_value() throws Exception {// GivenInteger test = 5;// ThenassertThat(test, is(5));}

3.2.7。 被形容為()

匹配器,用于覆蓋另一個匹配器的失敗輸出。 在需要自定義故障輸出時使用。 參數是失敗消息,原始Matcher,然后是將使用占位符%0,%1,%2格式化為失敗消息的所有值。

@Testpublic void test_describedAs() throws Exception {// GivenInteger actual = 7;Integer expected = 10;// ThenassertThat(actual, describedAs("input > %0", greaterThan(expected), expected));}

4。結論

現在,我們訪問了Hamcrest中定義的所有Matchers,并看到了每個匹配器的示例。 庫中有很多非常有用且功能強大的Matchers,尤其是當彼此結合使用時。 但是有時我們需要做的比現有的要多。 在下一個教程中,我們將研究如何創建自己的自定義Matchers,以擴展Hamcrest并使它更加有用!

翻譯自: https://www.javacodegeeks.com/2015/11/hamcrest-matchers-tutorial.html

總結

以上是生活随笔為你收集整理的Hamcrest Matchers教程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。