matchers依赖

本文是我们名为“ 用Mockito测试 ”的学院课程的一部分。

在本课程中,您将深入了解Mockito的魔力。 您将了解有关“模拟”,“间谍”和“部分模拟”的信息,以及它们相应的存根行为。 您还将看到使用测试双打和对象匹配器进行验证的过程。 最后,讨论了使用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”。

在“库”选项卡上,单击“添加外部Jar”按钮,然后导航到先前下载的所有hamcrest-jar。 选择罐子,它现在已添加到您的项目中并可供使用。

请注意,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()

Typesafe匹配器,如果输入集合为给定类型且为空,则匹配。

@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()

如果输入对象满足Bean约定并且具有具有指定名称的属性,并且该属性的值可选地与指定的匹配器匹配的匹配器。

物业名称

@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"));}

节点是否包含与输入XPath表达式匹配的节点,并且该节点的值是否与指定的匹配器匹配?

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

该节点是否在指定的名称空间中包含一个与输入XPath表达式匹配的节点,并且该节点的值是否与指定的匹配器匹配?

@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返回的顺序进行匹配。

@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

matchers依赖

matchers依赖_Hamcrest Matchers教程相关推荐

  1. matchers依赖_Hamcrest Matchers的高级创建

    matchers依赖 介绍 上一次 ,我讨论了Hamcrest Matcher是什么,如何使用以及如何制作. 在本文中,我将解释创建Hamcrest Matchers的更多高级步骤. 首先,我将分享如 ...

  2. matchers依赖_Hamcrest Matchers,Guava谓词和Builder设计模式

    matchers依赖 通常,在编码时,我们必须处理其中包含数十个字段的一些POJO对象. 很多时候,我们通过一个带有数十个参数的构造函数来初始化这些类,这以任何可能的想象的方式都是可怕的. 除此之外, ...

  3. matchers依赖_定制Hamcrest Matchers

    matchers依赖 本文是我们名为" 用Mockito测试 "的学院课程的一部分. 在本课程中,您将深入了解Mockito的魔力. 您将了解有关"模拟",&q ...

  4. maven asm 依赖配置_Maven教程_v20201119

    Maven是什么?它的作用有哪些? Maven安装配置和目录结构详解 创建Maven项目(cmd命令) Maven生成站点和报告文档(cmd命令) 使用MyEclipse建立maven项目 使用MyE ...

  5. guice依赖注入原理_Google Guice依赖注入示例教程

    guice依赖注入原理 Google Guice is the framework to automate the dependency injection in applications. If y ...

  6. fastjson所需的依赖_Fastjson使用教程

    介绍 Fastjson是一个Java语言编写的高性能功能完善的JSON库.它采用一种"假定有序快速匹配"的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的J ...

  7. maven snapshot依赖 打包_Maven教程2:Maven项目构建过程练习

    点击上方"Java技术前线",选择"置顶或者星标" 与你一起成长 上一篇只是简单介绍了一下maven入门的一些相关知识,这一篇主要是体验一下Maven高度自动化 ...

  8. PyInstaller 带静态依赖文件打包教程

  9. Hamcrest Matchers教程

    本文是我们名为" 用Mockito进行测试 "的学院课程的一部分. 在本课程中,您将深入了解Mockito的魔力. 您将了解有关"模拟","间谍&qu ...

最新文章

  1. ISME:比较基因组学揭示蓝藻进化和生境适应性特征
  2. UI设计师的实际工作流程是什么样的?
  3. linux sed命令替换目标字符串所在行整行为给定值
  4. 【代码笔记】iOS-点击城市中的tableView跳转到旅游景点的tableView,下面会有“显示”更多。...
  5. php基础教程 第八步循环补充
  6. linux重定向到文件permission denied
  7. 怎么用python做战斗机_关于python文件操作
  8. mysql 字符串 底层_Mysql 的索引底层原理及数据结构详解
  9. 我的java编程之路小小总结感想
  10. Spring框架 初步入门猜想
  11. Red Giant VFX Suite for mac(电影级视觉特效插件)
  12. 影视动画专业有木有c语言,那些头秃的专业,不了解一下?
  13. 一种很强的对联,看了让我想起高中时期那会儿对中文的崇拜!
  14. 数据库范式 1NF, 2NF, 3NF的问题与细解
  15. 迭代扩展卡尔曼滤波学习
  16. 揭秘社会工程学(让你免于被诈骗的命运)
  17. 让企业用上金融合规专有云,腾讯云专有云TCE矩阵来支招儿!
  18. ros 启动建图/导航-- Request for map failed; trying again...
  19. EasyExcel excel读取功能源码走读
  20. 湖南多校补题 状压dp

热门文章

  1. YbtOJ-选点构形【欧拉函数】
  2. CF932F-Escape Through Leaf【树上启发式合并,CDQ分治,斜率优化dp】
  3. CF496E-Distributing Parts【平衡树,贪心】
  4. P4145-上帝造题的七分钟2/花神游历各国【并查集,树状数组】
  5. P3441-[POI2006]MET-Subway【图论,贪心】
  6. codeforces1494 D. Dogeforces(构造)
  7. P2604 ZJOI2010 网络扩容,费用流裸题
  8. codeforces 935E Fafa and Ancient Mathematics 语法树、动态规划
  9. 2017上海金马五校 购买装备 贪心+二分Check
  10. 9、play中缓存的使用