matchers依赖_Hamcrest Matchers教程
matchers依賴
本文是我們名為“ 用Mockito測(cè)試 ”的學(xué)院課程的一部分。
在本課程中,您將深入了解Mockito的魔力。 您將了解有關(guān)“模擬”,“間諜”和“部分模擬”的信息,以及它們相應(yīng)的存根行為。 您還將看到使用測(cè)試雙打和對(duì)象匹配器進(jìn)行驗(yàn)證的過(guò)程。 最后,討論了使用Mockito的測(cè)試驅(qū)動(dòng)開(kāi)發(fā)(TDD),以了解該庫(kù)如何適合TDD的概念。 在這里查看 !
在本教程中,我們將研究Hamcrest Matcher庫(kù)以及如何將其與JUnit和Mockito集成。
目錄
1.什么是Hamcrest? 2.包括Hamcrest 3.認(rèn)識(shí)匹配者1.什么是Hamcrest?
Hamcrest是用于創(chuàng)建匹配對(duì)象的框架。 這些匹配器對(duì)象是謂詞,用于編寫(xiě)某些條件下可以滿足的規(guī)則。 它們通常用于自動(dòng)化測(cè)試中,盡管它們可以用于其他情況下,例如數(shù)據(jù)驗(yàn)證。 Hamcrest讓我們超越了簡(jiǎn)單的JUnit斷言,并使我們能夠編寫(xiě)非常具體的,易讀的驗(yàn)證代碼。
Hamcrest旨在使測(cè)試更具可讀性。 它充分利用靜態(tài)方法來(lái)創(chuàng)建斷言語(yǔ)法,該語(yǔ)法易于編寫(xiě)和理解。 當(dāng)與JUnit和Mockito結(jié)合使用時(shí),它使我們能夠編寫(xiě)清晰,簡(jiǎn)潔的測(cè)試,從而滿足良好的單元測(cè)試的特性,即“測(cè)試一件事”。
假設(shè)我們有一個(gè)String,我們想測(cè)試它是否與另一個(gè)預(yù)期的字符串相等,我們可以使用JUnit斷言來(lái)測(cè)試它:
assertEquals(expected, actual);在Hamcrest中,我們使用JUnit assertThat(valueUnderTest, matcher)方法。 此方法始終構(gòu)成Hamcrest斷言的基礎(chǔ); 我們斷言所測(cè)試的值滿足匹配謂詞。 要在最基本的水平上用hamcrest重寫(xiě)上述測(cè)試,我們可以編寫(xiě):
assertThat(actual, equalTo(expected));注意assertThat約定將被測(cè)的實(shí)際值作為第一個(gè)參數(shù),這與assertEquals約定相反。 這是對(duì)可讀性的改進(jìn),但是Hamcrest還以is()匹配器的形式為我們提供了一些不錯(cuò)的語(yǔ)法糖。 該匹配器本身不執(zhí)行任何操作,它只是中繼其輸入匹配器的結(jié)果,從而使您的斷言代碼可以像英語(yǔ)一樣讀取。 讓我們使用is()重寫(xiě)上面的內(nèi)容:
assertThat(actual, is(equalTo(expected)));很好,很可讀!
Hamcrest的匹配器失敗時(shí),它會(huì)生成詳細(xì)的輸出,并指定期望值和實(shí)際值,以幫助您確定測(cè)試失敗的原因。 查看以下測(cè)試用例:
@Testpublic void test_failed() throws Exception {// GivenInteger number = 7;// ThenassertThat(number, greaterThan(10));}顯然,該測(cè)試將失敗,但是Hamcrest將提供有關(guān)失敗的詳細(xì)信息:
java.lang.AssertionError: Expected: a value greater than <10>but: <7> was less than <10>在本教程中,我們將遵循僅將一個(gè)斷言作為單元測(cè)試一部分的約定。 這似乎是重復(fù)的,特別是在許多測(cè)試中測(cè)試的設(shè)置部分相同的情況下,但是這是單元測(cè)試中的良好做法。 它使我們能夠創(chuàng)建針對(duì)性的測(cè)試-僅當(dāng)單個(gè)斷言失敗時(shí),測(cè)試才會(huì)失敗,其他所有斷言將繼續(xù)執(zhí)行。 它使我們能夠創(chuàng)建可讀的測(cè)試-我們可以一目了然地看到測(cè)試的目的。 它使我們能夠創(chuàng)建記錄代碼的測(cè)試-我們可以使用表達(dá)測(cè)試目的的測(cè)試名稱,從而傳達(dá)測(cè)試的詳細(xì)目的(請(qǐng)考慮customer_should_have_balance_updated_by_input_order_amount()而不是verifyOrderMethod() )。 它使我們能夠創(chuàng)建不易碎的測(cè)試–如果測(cè)試做得太多,則如果更改了不相關(guān)的功能,它可能會(huì)中斷,從而迫使我們重寫(xiě)測(cè)試只是為了使其再次正常工作,而無(wú)需更改實(shí)際的被測(cè)代碼。
如果我們遵循“測(cè)試一件事”的習(xí)慣,我們將在未來(lái)編寫(xiě)出更好的單元測(cè)試!
2.包括Hamcrest
如果您使用的是Maven,則可以將Hamcrest添加到您的項(xiàng)目中,并且對(duì)pom.xml具有以下依賴性
<dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-all</artifactId><version>1.3</version></dependency>如果您使用的是Gradle,請(qǐng)?zhí)砑右韵聝?nèi)容
dependencies {testCompile "org.hamcrest:hamcrest-all:1.3"}要將hamcrest直接添加到項(xiàng)目的類路徑中,您可以從https://code.google.com/p/hamcrest/下載hamcrest-all-1.3.jar到硬盤(pán)驅(qū)動(dòng)器上的某個(gè)位置。
右鍵單擊您的eclipse項(xiàng)目,然后選擇“屬性”,然后在左窗格中選擇“ Java Build Path”,然后在右側(cè)選擇“ Libraries”。
在“庫(kù)”選項(xiàng)卡上,單擊“添加外部Jar”按鈕,然后導(dǎo)航到先前下載的所有hamcrest-jar。 選擇罐子,它現(xiàn)在已添加到您的項(xiàng)目中并可供使用。
請(qǐng)注意,JUnit與簡(jiǎn)化版本的Hamcrest(Hamcrest Core)捆綁在一起,因此,如果JUnit在類路徑上的Hamcrest之前出現(xiàn),則編譯器將選擇該版本。 為了解決這個(gè)問(wèn)題,請(qǐng)確保Hamcrest在類路徑上的JUnit之前出現(xiàn)。 您可以在Maven中通過(guò)在所有其他依賴項(xiàng)之前列出hamcrest-all依賴項(xiàng)來(lái)實(shí)現(xiàn)此目的。
與Mockito靜態(tài)方法一樣,我們可以通過(guò)啟動(dòng)Window-> Preferences并將Hamcrest庫(kù)添加到Eclipse內(nèi)容輔助中,并轉(zhuǎn)到左側(cè)導(dǎo)航欄中的Java / Editor / Content Assist / Favorites。 然后,按照?qǐng)D1添加以下內(nèi)容作為“ New Type…”
- org.hamcrest.Matchers
啟動(dòng)Window-> Preferences,然后轉(zhuǎn)到左側(cè)導(dǎo)航欄中的Java / Editor / Content Assist / Favorites。 然后,按照?qǐng)D1添加以下內(nèi)容作為“ New Type…”
圖1 – Content Assist收藏夾
3.認(rèn)識(shí)匹配者
Hamcrest提供了一個(gè)靜態(tài)工廠方法庫(kù),用于在org.hamcrest.Matchers類中創(chuàng)建Matchers,因此您可以通過(guò)靜態(tài)導(dǎo)入引入所有Matchers
import static org.hamcrest.Matchers.* 但是,如果這樣做,則存在命名沖突的風(fēng)險(xiǎn),因?yàn)镠amcrest和Mockito都提供靜態(tài)的any()方法,因此建議導(dǎo)入您單獨(dú)使用的每個(gè)靜態(tài)方法。
現(xiàn)在,我們將在Hamcrest Matchers庫(kù)中查看所有可用的Matchers。 它們將分為兩大類: 用于測(cè)試值的匹配器(簡(jiǎn)單),以及用于組合其他匹配器(聚合)的匹配器。
簡(jiǎn)單匹配器
以下匹配器主要用于測(cè)試輸入值。
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()
數(shù)組的各種匹配器,數(shù)組的長(zhǎng)度必須匹配匹配器的數(shù)量,并且它們的順序很重要。
數(shù)組是否按照輸入到匹配器的順序包含所有給定項(xiàng)目?
@Testpublic void test_arrayContaining_items() throws Exception {// GivenString[] strings = {"why", "hello", "there"};// ThenassertThat(strings, is(arrayContaining("why", "hello", "there")));}數(shù)組是否包含按順序匹配匹配器輸入列表的項(xiàng)目?
@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)));}數(shù)組是否按順序包含與輸入vararg匹配器匹配的項(xiàng)目?
@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()
數(shù)組的各種匹配器,數(shù)組的長(zhǎng)度必須匹配匹配器的數(shù)量,但是它們的順序并不重要。
數(shù)組是否包含所有給定項(xiàng)?
@Testpublic void test_arrayContainingInAnyOrder_items() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenassertThat(strings, is(arrayContainingInAnyOrder("hello", "there", "why")));}數(shù)組中是否包含與Matchers的輸入集合匹配的項(xiàng)目?
@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)));}數(shù)組是否包含與輸入vararg匹配器匹配的項(xiàng)目?
@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()
各種匹配器,用于檢查數(shù)組是否具有特定長(zhǎng)度。
輸入數(shù)組是否具有指定的長(zhǎng)度?
@Testpublic void test_arrayWithSize_exact() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenassertThat(strings, is(arrayWithSize(3)));}輸入數(shù)組的長(zhǎng)度是否與指定的匹配項(xiàng)匹配?
@Testpublic void test_arrayWithSize_matcher() throws Exception {// GivenString[] strings = { "why", "hello", "there" };// ThenassertThat(strings, is(arrayWithSize(greaterThan(2))));}3.1.6。 相近()
可以與Double或BigDecimal一起使用的匹配器,以檢查某個(gè)值是否在期望值的指定誤差范圍內(nèi)。
雙
@Testpublic void test_closeTo_double() throws Exception {// GivenDouble testValue = 6.3;// ThenassertThat(testValue, is(closeTo(6, 0.5)));}大十進(jìn)制
@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()
創(chuàng)建一個(gè)Comparable匹配器,嘗試使用輸入值的compareTo()方法匹配輸入匹配器值。 如果compareTo()方法為輸入的匹配器值返回0,則匹配器將匹配,否則將不匹配。
@Testpublic void test_comparesEqualTo() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, comparesEqualTo("value"));}3.1.8。 contains()
各種匹配器可用于檢查輸入Iterable是否包含值。 值的順序很重要,并且Iterable中的項(xiàng)目數(shù)必須與要測(cè)試的值數(shù)相匹配。
輸入列表是否按順序包含所有值?
@Testpublic void test_contains_items() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenassertThat(strings, contains("why", "hello", "there"));}輸入列表中是否包含按順序匹配輸入匹配器列表中所有匹配器的項(xiàng)目?
@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));}輸入列表中是否僅包含與輸入匹配項(xiàng)匹配的一項(xiàng)?
@Testpublic void test_contains_single_matcher() throws Exception {// GivenList<String> strings = Arrays.asList("hello");// ThenassertThat(strings, contains(startsWith("he")));}輸入列表中是否包含按順序匹配輸入vararg匹配器中所有匹配器的項(xiàng)?
@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中的項(xiàng)目數(shù)必須與要測(cè)試的值數(shù)相匹配。
輸入列表是否以任何順序包含所有值?
@Testpublic void test_containsInAnyOrder_items() throws Exception {// GivenList<String> strings = Arrays.asList("why", "hello", "there");// ThenassertThat(strings, containsInAnyOrder("hello", "there", "why"));}輸入列表中是否包含與輸入匹配器列表中的所有匹配器按任何順序匹配的項(xiàng)目?
@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匹配器中所有匹配器的項(xiàng)目?
@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()
如果被測(cè)字符串包含給定的子字符串,則匹配的匹配器。
@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()
如果輸入數(shù)組的長(zhǎng)度為0,則匹配的匹配器。
@Testpublic void test_emptyArray() throws Exception {// GivenString[] testArray = new String[0];// ThenassertThat(testArray, is(emptyArray()));}3.1.13。 emptyCollectionOf()
Typesafe匹配器,如果輸入集合為給定類型且為空,則匹配。
@Testpublic void test_emptyCollectionOf() throws Exception {// GivenSet<String> testCollection = new HashSet<>();// ThenassertThat(testCollection, is(emptyCollectionOf(String.class)));}3.1.14。 emptyIterable()
如果輸入Iterable沒(méi)有值,則匹配的匹配器。
@Testpublic void test_emptyIterable() throws Exception {// GivenSet<String> testCollection = new HashSet<>();// ThenassertThat(testCollection, is(emptyIterable()));}3.1.15。 emptyIterableOf()
Typesafe Matcher,如果輸入的Iterable沒(méi)有值且為給定類型,則匹配。
@Testpublic void test_emptyIterableOf() throws Exception {// GivenSet<String> testCollection = new HashSet<>();// ThenassertThat(testCollection, is(emptyIterableOf(String.class)));}3.1.16。 以。。結(jié)束()
如果輸入String以給定的子字符串結(jié)尾,則匹配的匹配器。
@Testpublic void test_endsWith() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, endsWith("lue"));}3.1.17。 等于()
如果輸入值在邏輯上等于給定測(cè)試值,則匹配的匹配器。 也可以在數(shù)組上使用,在這種情況下,它將檢查數(shù)組的長(zhǎng)度并確保輸入測(cè)試數(shù)組中的所有值在邏輯上都等于指定數(shù)組的值。
單值。
@Testpublic void test_equalTo_value() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, equalTo("value"));}數(shù)組。
@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而忽略大小寫(xiě),則匹配的匹配器。
@Testpublic void test_equalToIgnoringCase() throws Exception {// GivenString testValue = "value";// ThenassertThat(testValue, equalToIgnoringCase("VaLuE"));}3.1.19。 equalToIgnoringWhiteSpace()
如果輸入的String值等于指定的String而不匹配多余的空格,則匹配該匹配器。 忽略所有前導(dǎo)和尾隨空格,并將所有剩余空格折疊為單個(gè)空格。
@Testpublic void test_equalToIgnoringWhiteSpace() throws Exception {// GivenString testValue = "this is my value ";// ThenassertThat(testValue, equalToIgnoringWhiteSpace("this is my value"));}3.1.20。 eventFrom()
如果輸入EventObject來(lái)自給定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。 比...更棒()
如果輸入測(cè)試值大于指定值,則匹配的匹配器。
@Testpublic void test_greaterThan() throws Exception {// GivenInteger testValue = 5;// ThenassertThat(testValue, is(greaterThan(3)));}3.1.22。 GreaterThanOrEqual()
如果輸入測(cè)試值大于或等于指定值,則匹配的匹配器。
@Testpublic void test_greaterThanOrEqualTo() throws Exception {// GivenInteger testValue = 3;// ThenassertThat(testValue, is(greaterThanOrEqualTo(3)));}3.1.23。 hasEntry()
如果給定映射包含與指定鍵和值匹配的條目,則匹配器或匹配器。
實(shí)際值
@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具有至少一項(xiàng)與指定值或匹配器匹配的項(xiàng),則匹配器。
實(shí)際價(jià)值
@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()
如果輸入數(shù)組具有至少一個(gè)與指定值或匹配器匹配的項(xiàng)目,則匹配的匹配器。
實(shí)際價(jià)值
@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具有任意順序的所有指定值或匹配器,則匹配的匹配器。
實(shí)際值
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具有至少一個(gè)與指定值或匹配項(xiàng)匹配的鍵,則匹配的匹配項(xiàng)。
實(shí)際價(jià)值
@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()
如果輸入對(duì)象滿足Bean約定并且具有具有指定名稱的屬性,并且該屬性的值可選地與指定的匹配器匹配的匹配器。
物業(yè)名稱
@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具有指定的大小,或者它的大小與指定的匹配器匹配,則匹配器。
實(shí)際價(jià)值
匹配器
@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()
如果輸入對(duì)象的toString()方法匹配指定的String或輸入匹配器,則匹配的匹配器。
正常價(jià)值
@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具有至少一個(gè)與指定值或匹配器匹配的值,則匹配的匹配器。
實(shí)際價(jià)值
@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節(jié)點(diǎn)滿足輸入XPath表達(dá)式,則匹配的匹配器。
節(jié)點(diǎn)是否包含與輸入XPath表達(dá)式匹配的節(jié)點(diǎn)?
@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"));}節(jié)點(diǎn)是否包含與輸入XPath表達(dá)式匹配的節(jié)點(diǎn),并且該節(jié)點(diǎn)的值是否與指定的匹配器匹配?
@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")));}節(jié)點(diǎn)是否在指定的名稱空間中包含與輸入XPath表達(dá)式匹配的節(jié)點(diǎn)?
@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)); }該節(jié)點(diǎn)是否在指定的名稱空間中包含一個(gè)與輸入XPath表達(dá)式匹配的節(jié)點(diǎn),并且該節(jié)點(diǎn)的值是否與指定的匹配器匹配?
@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()
如果輸入對(duì)象是給定類型,則匹配器。
@Test public void test_instanceOf() throws Exception {// GivenObject string = "Hello, World!";// ThenassertThat(string, instanceOf(String.class)); }3.1.34。 isEmptyOrNullString()
當(dāng)輸入字符串為空或null時(shí)匹配的匹配器。
@Test public void test_isEmptyOrNullString() throws Exception {// GivenString emptyString = ";String nullString = null;// ThenassertThat(emptyString, isEmptyOrNullString());assertThat(nullString, isEmptyOrNullString()); }3.1.35。 isEmptyString()
當(dāng)輸入字符串為空時(shí)匹配的匹配器。
@Test public void test_isEmptyString() throws Exception {// GivenString emptyString = ";// ThenassertThat(emptyString, isEmptyString()); }3.1.36。 isIn()
當(dāng)在給定的Collection或Array中找到輸入項(xiàng)時(shí)匹配的匹配器。
@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。 是其中之一()
當(dāng)輸入對(duì)象是給定對(duì)象之一時(shí)匹配的匹配器。
@Test public void test_isOneOf() throws Exception {// ThenassertThat(4, isOneOf(3,4,5)); }3.1.38。 iterableWithSize()
當(dāng)輸入Iterable具有指定大小時(shí)匹配或與指定大小匹配器匹配的匹配器。
實(shí)際價(jià)值
@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方法匹配輸入對(duì)象小于指定值的可比較對(duì)象。
@Test public void test_lessThan() throws Exception {// ThenassertThat("apple", lessThan("zoo")); }3.1.40。 lessThanOrEqualTo()
匹配器,使用compareTo方法匹配輸入對(duì)象小于或等于指定值的可比較對(duì)象。
@Test public void test_lessThanOrEqualTo() throws Exception {// ThenassertThat(2, lessThanOrEqualTo(2)); }3.1.41。 不()
包裹現(xiàn)有匹配器并反轉(zhuǎn)其匹配邏輯的匹配器
@Test public void test_not_matcher() throws Exception {// ThenassertThat("zoo", not(lessThan("apple"))); }當(dāng)與值而不是匹配器一起使用時(shí),也是not(equalTo(...))的別名
@Test public void test_not_value() throws Exception {// ThenassertThat("apple", not("orange")); }3.1.42。 notNullValue()
當(dāng)輸入值不為null時(shí)匹配的匹配器。
@Test public void test_notNullValue() throws Exception {// ThenassertThat("apple", notNullValue()); }3.1.43。 nullValue()
當(dāng)輸入值為null時(shí)匹配的匹配器。
@Test public void test_nullValue() throws Exception {// GivenObject nothing = null;// ThenassertThat(nothing, nullValue()); }3.1.44。 sameInstance()
當(dāng)輸入對(duì)象與指定值相同的實(shí)例時(shí)匹配的匹配器。
@Test public void test_sameInstance() throws Exception {// GivenObject one = new Object();Object two = one;// ThenassertThat(one, sameInstance(two)); }3.1.45。 samePropertyValuesAs()
當(dāng)輸入Bean具有與指定Bean相同的屬性值時(shí)匹配的匹配項(xiàng),即,如果被測(cè)Bean上具有屬性,則它們必須存在,并且具有與在測(cè)試條件中指定的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;} }我們可以編寫(xiě)以下測(cè)試:
@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。 以。。開(kāi)始()
如果輸入字符串以給定前綴開(kāi)頭的匹配項(xiàng)。
@Testpublic void test_startsWith() throws Exception {// GivenString test = "Beginnings are important!";// ThenassertThat(test, startsWith("Beginning"));}3.1.47。 stringContainsInOrder()
匹配器,如果輸入的String包含給定的Iterable中的子字符串,則按從Iterable返回的順序進(jìn)行匹配。
@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()
當(dāng)輸入對(duì)象與指定值相同的實(shí)例時(shí)匹配的匹配器。 行為與“ sameInstance()”相同
@Test public void test_theInstance() throws Exception {// GivenObject one = new Object();Object two = one;// ThenassertThat(one, theInstance(two)); }3.1.49。 typeCompatibleWith()
當(dāng)輸入類型的對(duì)象可以分配給指定基本類型的引用時(shí)匹配的匹配器。
@Testpublic void test_typeCompatibleWith() throws Exception {// GivenInteger integer = 3;// ThenassertThat(integer.getClass(), typeCompatibleWith(Number.class));}簡(jiǎn)單匹配器結(jié)合其他匹配器
以下匹配器主要用于組合其他匹配器。
3.2.1。 所有的()
當(dāng)所有輸入Matchers都匹配時(shí)匹配的Matcher的行為類似于邏輯AND。 可以使用單個(gè)Matchers或Iterable Matchers。
個(gè)人匹配器
@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。 任何()
當(dāng)任何輸入匹配器匹配時(shí)匹配的匹配器,其行為類似于邏輯或。 可以使用單個(gè)Matchers或Iterable Matchers。
個(gè)人匹配器
@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()
當(dāng)輸入數(shù)組的元素分別使用指定的Matchers依次進(jìn)行匹配時(shí)匹配的Matcher。 匹配器的數(shù)量必須等于數(shù)組的大小。
@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。 都()
匹配器,當(dāng)與它的可組合匹配器.and()結(jié)合使用時(shí),將在兩個(gè)指定匹配器匹配時(shí)匹配。
@Testpublic void test_both() throws Exception {// GivenString test = "Hello, world!";// ThenassertThat(test, both(startsWith("Hello")).and(endsWith("world!")));}3.2.5。 要么()
匹配器,當(dāng)與它的可組合匹配器.or()結(jié)合使用時(shí),如果指定的匹配器匹配,則匹配器。
@Testpublic void test_either() throws Exception {// GivenString test = "Hello, world!";// ThenassertThat(test, either(startsWith("Hello")).or(endsWith("universe!")));}3.2.6。 is()
當(dāng)輸入匹配器匹配時(shí)匹配的匹配器,只是為了方便起見(jiàn),使斷言更像英語(yǔ)。
@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。 被描述成()
匹配器,用于覆蓋另一個(gè)匹配器的失敗輸出。 在需要自定義故障輸出時(shí)使用。 參數(shù)是失敗消息,原始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。結(jié)論
現(xiàn)在,我們?cè)L問(wèn)了Hamcrest中定義的所有Matchers,并看到了每個(gè)匹配器的實(shí)例。 庫(kù)中有很多非常有用且功能強(qiáng)大的Matchers,尤其是當(dāng)彼此結(jié)合使用時(shí)。 但是有時(shí)候我們需要做的比現(xiàn)有的還要多。 在下一個(gè)教程中,我們將研究如何創(chuàng)建自己的自定義Matchers,以擴(kuò)展Hamcrest并使它更加有用!
翻譯自: https://www.javacodegeeks.com/2015/11/hamcrest-matchers-tutorial.html
matchers依賴
總結(jié)
以上是生活随笔為你收集整理的matchers依赖_Hamcrest Matchers教程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 打印机驱动(打印机驱动在电脑哪里找)
- 下一篇: apache lucene_Apache