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收藏夹

图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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/355985.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

win7下安装 python2 和python3

一直纠结于选择py2还是py3&#xff0c;不如在同一系统下安装两个版本就好了。 1、安装python2.7和python3.5 直接到官网https://www.python.org/下载&#xff0c;安装就可以了。 2.安装比较简单&#xff0c;点exe文件一直下一步就可以了&#xff08;注意&#xff1a;安装的时候…

谈谈你对oracle的认识,对Oracle存储过程的几点认识

1、写Oracle存储过程时最好不要在其中写Commit语句。一般调用程序会自动Commit数据&#xff0c;比如用NHibernate调用的时候&#xff0c;NHibernate就会自动Commi1、写Oracle存储过程时最好不要在其中写Commit语句。一般调用程序会自动Commit数据&#xff0c;&#xff0c;比如用…

jmeter负载测试测试_Apache JMeter:随心所欲进行负载测试

jmeter负载测试测试这是有关使用Apache JMeter进行负载测试的第二篇文章&#xff0c;请在此处阅读第一篇文章&#xff1a; 有关对关系数据库进行负载测试的分步教程。 JMeter有很多采样器 。 如果您需要JMeter不提供的采样器&#xff0c;则可以编写您的自定义采样器。 &#xf…

VM虚拟机ping不通局域网其他主机的解决办法

1 我的笔记本的无线网卡是自动获取IP&#xff0c;并且是通过无线网卡上网。 2 我的有线网卡是通过自己设定IP跟局域网的其他机器连通。当前设定的IP为172.16.17.2 3我需要连接的局域网另一个主机为172.16.17.8&#xff0c;现在测试主机跟这个局域网的另一台主机是可以ping通的。…

linux命令画圣诞树图片,以 Linux 的方式庆祝圣诞节

原标题&#xff1a;以 Linux 的方式庆祝圣诞节当前正是假日季&#xff0c;很多人可能已经在庆祝圣诞节了。祝你圣诞快乐&#xff0c;新年快乐。为了延续节日氛围&#xff0c;我将向你展示一些非常棒的圣诞主题的 Linux 壁纸。在呈现这些壁纸之前&#xff0c;先来看一棵 Linux 终…

LINQ 学习路程 -- 查询语法 LINQ Query Syntax

1.查询语法 Query Syntax: from <range variable> in <IEnumerable<T> or IQueryable<T> Collection><Standard Query Operators> <lambda expression><select or groupBy operator> <result formation> // string collectio…

linux 权限提示信息,命令行快速提示:权限进阶 | Linux 中国

原标题&#xff1a;命令行快速提示&#xff1a;权限进阶 | Linux 中国本部分介绍使用权限管理文件访问和共享的其他方法。-- Paul W. Frields前一篇文章。本部分介绍使用权限管理文件访问和共享的其他方法。它建立在前一篇文章中的知识和示例的基础上&#xff0c;所以如果你还没…

nginx正确服务react-router应用

如今React应用普遍使用react-router作为路由管理&#xff0c;在开发端webpack自带的express服务器下运行和测试表现均正常&#xff0c;部署到线上的nginx服务器后&#xff0c;还需要对该应用在nginx的配置里作相应调整&#xff0c;否则浏览器将不能正常使用该应用&#xff0c;表…

linux中服务器之间的跳转,linux之***服务器间ip隧道跳转多ip路由走向分流(系真实案例)...

本文系统Centos6.0&#xff1b;这里的***服务以pptpd为例&#xff1b;其中底层涉及到pptpdfreeradiusmysql认证&#xff1b;本文系真实案例&#xff1b;leader需求大多是这样的&#xff0c;节约成本还要达到所需要的效果&#xff1b;没办法&#xff0c;总的做个效果出来&#x…

使用JBoss EAP 7的HTTP / 2

就在几天前&#xff0c;新的JBoss EAP 7 ALPHA版本已经发布。 而且我已经写过关于如何开始使用它的博客。 一个非常有趣的部分是HTTP / 2支持&#xff0c;它已作为技术预览添加。 它由新的Web服务器Untertow提供。 HTTP / 2通过压缩头并在同一TCP连接上多路复用多个流来减少延迟…

linux树莓派 ssh密码,树莓派之SSH连接经验

打开SSH服务执行raspi-configsudo raspi-config选择InterfacingOptions选项&#xff0c;回车选择SSH&#xff0c;回车Windows下客户端推荐使用putty这个免费开源的SSH客户端。下载地址在红框处填入树莓派的IP地址&#xff0c;点击右下角的Open即可。不过&#xff0c;putty的默认…

Linux读取SSD的smart信息,使用smartmontools查看SSD的“秘密”信息

仍然担心看不到sm841中的温度吗&#xff1f;您是否仍对Toshiba Q pro看不见写入量和使用寿命值感到不安&#xff1f;为了查看M4 / 00的写入量&#xff0c;您是否仍在使用C300固件升级程序重新启动到纯DOS并麻烦地运行命令&#xff1f;想知道在协议级别上SSD出了什么问题吗&…

锁定机制和数据并发管理(笔记)

共享锁和排它锁 排它锁&#xff1a;当某一个会话正在更新某一行&#xff0c;为了防止其他会话修改这一行&#xff0c;这行会被锁定这种锁称为排他锁。被排他锁锁定的行仍然可以被其他会话读取。 共享锁&#xff1a;在一个表上放置共享锁的目的是为了防止其他会话获得这个表上的…

【react.js + hooks】useGuide 创建用户引导视图

有的时候用户可能对网站上的一些操作流程感到困惑&#xff0c;这时候我们需要为用户创建引导视图。为了插入指引而专门去更改组件的渲染函数&#xff0c;显然是不合逻辑的&#xff0c;创建指引视图应该是一种对源代码低侵入的行为&#xff0c;我们可以遵循某一套约定&#xff0…

使用递归算法结合数据库解析成java树形结构

使用递归算法结合数据库解析成java树形结构 1、准备表结构及对应的表数据a、表结构&#xff1a; create table TB_TREE ( CID NUMBER not null, CNAME VARCHAR2(50), PID NUMBER //父节点 ) b、表数据&#xff1a; insert into tb_tree (CID, CNAME, PID) values (1, 中国, 0);…

ug11 linux,UG11.0升级包MP02Win#Linux系统下载就上UG网

UG11.0软件又出升级包啦&#xff01;抽空可以为NX升级啦&#xff0c;从11.0发布到现在&#xff0c;近三个月了&#xff0c;每一次版本的更新&#xff0c;都会带来较多功能的改善&#xff0c;以及对错误BUG的有效处理&#xff0c;下图为升级后的UG11.0软件&#xff1b;UG11.0升级…

akka 异常处理_使用Akka处理1000万条消息

akka 异常处理Akka演员承诺并发。 有什么更好的模拟方法&#xff0c;看看使用商品硬件和软件处理1000万条消息需要花费多少时间&#xff0c;而无需进行任何低级调整。我用Java编写了整个1000万条消息的处理过程&#xff0c;整个结果令我惊讶。 当我在具有i5 – 4核心&#xff0…

20155330 2016-2017-2 《Java程序设计》第五周学习总结

20155330 2016-2017-2 《Java程序设计》第五周学习总结 教材学习内容总结 学习目标 理解异常架构掌握try...catch...finally处理异常的方法会用throw,throws理解Collection和Map架构会用常见的数据结构和算法了解Lambada和泛型第八章 章节主要内容 小结 Throwwable定义了取错误…

yum安装odbc驱动linux,在CentOS上离线配置PostgreSQL ODBC数据源

一、问题提出内网的一台CentOS服务器&#xff0c;需配置PostgreSQL ODBC。如果可以连接Internet&#xff0c;此工作很容易&#xff0c;使用yum install自动安装相应依赖包后简单配置即可。但当置于内网环境时&#xff0c;事情就有些麻烦&#xff0c;需要事先手工下载各个依赖包…

pcie组raid linux,PCIe 4.0有多强大?组RAID 0阵列之后惊呆了

技嘉在6月16日21:00正式上市了全系列B550系列主板&#xff0c;B550系列主板属于AMD中端系列芯片组&#xff0c;能原生支持PCIe 4.0技术&#xff0c;而这次技嘉B550 AORUS MASTER主板更是不得了&#xff0c;提供了3个支持PCIe 4.0技术的M.2接口&#xff0c;你还可以组RAID 0阵列…