matchers依赖_Hamcrest Matchers教程

matchers依赖

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

在本课程中,您将深入了解Mockito的魔力。 您将了解有关“模拟”,“间谍”和“部分模拟”的信息,以及它们相应的存根行为。 您还将看到使用测试双打和对象匹配器进行验证的过程。 最后,讨论了使用Mockito的测试驱动开发(TDD),以了解该库如何适合TDD的概念。 在这里查看

在本教程中,我们将研究Hamcrest Matcher库以及如何将其与JUnit和Mockito集成。

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的匹配器失败时,它会生成详细的输出,并指定期望值和实际值,以帮助您确定测试失败的原因。 查看以下测试用例:

@Test
    public void test_failed() throws Exception {
        // Given
        Integer number = 7;

        // Then
        assertThat(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收藏夹

图1 – Content Assist收藏夹

3.认识匹配者

Hamcrest提供了一个静态工厂方法库,用于在org.hamcrest.Matchers类中创建Matchers,因此您可以通过静态导入引入所有Matchers

import static org.hamcrest.Matchers.*

但是,如果这样做,则存在命名冲突的风险,因为Hamcrest和Mockito都提供静态的any()方法,因此建议导入您单独使用的每个静态方法。
现在,我们将在Hamcrest Matchers库中查看所有可用的Matchers。 它们将分为两大类: 用于测试值的匹配器(简单),以及用于组合其他匹配器(聚合)的匹配器。

简单匹配器

以下匹配器主要用于测试输入值。

3.1.1。 任何()

匹配给定类型的任何变量。

@Test
	public void test_any() throws Exception {
		// Given
		String myString = "hello";
		
		// Then
		assertThat(myString, is(any(String.class)));		
	}
3.1.2。 任何()

匹配任何东西。

@Test
	public void test_anything() throws Exception {
		// Given
		String myString = "hello";
		Integer four = 4;
		
		// Then
		assertThat(myString, is(anything()));
		assertThat(four, is(anything()));
	}
3.1.3。 arrayContaining()

数组的各种匹配器,数组的长度必须匹配匹配器的数量,并且它们的顺序很重要。

数组是否按照输入到匹配器的顺序包含所有给定项目?

@Test
	public void test_arrayContaining_items() throws Exception {
		// Given
		String[] strings = {"why", "hello", "there"};
		
		// Then
		assertThat(strings, is(arrayContaining("why", "hello", "there")));
	}

数组是否包含按顺序匹配匹配器输入列表的项目?

@Test
	public void test_arrayContaining_list_of_matchers() throws Exception {
		// Given
		String[] strings = {"why", "hello", "there"};
		
		// Then
		java.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匹配器匹配的项目?

@Test
	public void test_arrayContaining_matchers() throws Exception {
		// Given
		String[] strings = {"why", "hello", "there"};
		
		// Then
		assertThat(strings, is(arrayContaining(startsWith("wh"), equalTo("hello"), endsWith("here"))));
	}
3.1.4。 arrayContainingInAnyOrder()

数组的各种匹配器,数组的长度必须匹配匹配器的数量,但是它们的顺序并不重要。

数组是否包含所有给定项?

@Test
	public void test_arrayContainingInAnyOrder_items() throws Exception {
		// Given
		String[] strings = { "why", "hello", "there" };

		// Then
		assertThat(strings, is(arrayContainingInAnyOrder("hello", "there", "why")));
	}

数组中是否包含与Matchers的输入集合匹配的项目?

@Test
	public void test_arrayContainingInAnyOrder_collection_of_matchers() throws Exception {
		// Given
		String[] strings = { "why", "hello", "there" };

		// Then
		Set<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匹配器匹配的项目?

@Test
	public void test_arrayContainingInAnyOrder_matchers() throws Exception {
		// Given
		String[] strings = { "why", "hello", "there" };

		// Then
		assertThat(strings, is(arrayContainingInAnyOrder(endsWith("lo"), startsWith("the"), equalTo("why"))));
	}
3.1.5。 arrayWithSize()

各种匹配器,用于检查数组是否具有特定长度。

输入数组是否具有指定的长度?

@Test
	public void test_arrayWithSize_exact() throws Exception {
		// Given
		String[] strings = { "why", "hello", "there" };

		// Then
		assertThat(strings, is(arrayWithSize(3)));
	}

输入数组的长度是否与指定的匹配项匹配?

@Test
	public void test_arrayWithSize_matcher() throws Exception {
		// Given
		String[] strings = { "why", "hello", "there" };

		// Then
		assertThat(strings, is(arrayWithSize(greaterThan(2))));
	}
3.1.6。 相近()

可以与Double或BigDecimal一起使用的匹配器,以检查某个值是否在期望值的指定误差范围内。

@Test
	public void test_closeTo_double() throws Exception {
		// Given
		Double testValue = 6.3;

		// Then
		assertThat(testValue, is(closeTo(6, 0.5)));
	}

大十进制

@Test
	public void test_closeTo_bigDecimal() throws Exception {
		// Given
		BigDecimal testValue = new BigDecimal(324.0);

		// Then
		assertThat(testValue, is(closeTo(new BigDecimal(350), new BigDecimal(50))));
	}
3.1.7。 comparesEqualTo()

创建一个Comparable匹配器,尝试使用输入值的compareTo()方法匹配输入匹配器值。 如果compareTo()方法为输入的匹配器值返回0,则匹配器将匹配,否则将不匹配。

@Test
	public void test_comparesEqualTo() throws Exception {
		// Given
		String testValue = "value";

		// Then
		assertThat(testValue, comparesEqualTo("value"));
	}
3.1.8。 contains()

各种匹配器可用于检查输入Iterable是否包含值。 值的顺序很重要,并且Iterable中的项目数必须与要测试的值数相匹配。

输入列表是否按顺序包含所有值?

@Test
	public void test_contains_items() throws Exception {
		// Given
		List<String> strings = Arrays.asList("why", "hello", "there");

		// Then
		assertThat(strings, contains("why", "hello", "there"));
	}

输入列表中是否包含按顺序匹配输入匹配器列表中所有匹配器的项目?

@Test
	public void test_contains_list_of_matchers() throws Exception {
		// Given
		List<String> strings = Arrays.asList("why", "hello", "there");

		// Then
		List<org.hamcrest.Matcher<? super String>> matchers = new ArrayList<>();
		matchers.add(startsWith("wh"));
		matchers.add(endsWith("lo"));
		matchers.add(equalTo("there"));
		assertThat(strings, contains(matchers));
	}

输入列表中是否仅包含与输入匹配项匹配的一项?

@Test
	public void test_contains_single_matcher() throws Exception {
		// Given
		List<String> strings = Arrays.asList("hello");

		// Then
		assertThat(strings, contains(startsWith("he")));
	}

输入列表中是否包含按顺序匹配输入vararg匹配器中所有匹配器的项?

@Test
	public void test_contains_matchers() throws Exception {
		// Given
		List<String> strings = Arrays.asList("why", "hello", "there");

		// Then
		assertThat(strings, contains(startsWith("why"), endsWith("llo"), equalTo("there")));
	}
3.1.9。 containsInAnyOrder()

各种匹配器可用于检查输入Iterable是否包含值。 值的顺序并不重要,但是Iterable中的项目数必须与要测试的值数相匹配。

输入列表是否以任何顺序包含所有值?

@Test
	public void test_containsInAnyOrder_items() throws Exception {
		// Given
		List<String> strings = Arrays.asList("why", "hello", "there");

		// Then
		assertThat(strings, containsInAnyOrder("hello", "there", "why"));
	}

输入列表中是否包含与输入匹配器列表中的所有匹配器按任何顺序匹配的项目?

@Test
	public void test_containsInAnyOrder_list_of_matchers() throws Exception {
		// Given
		List<String> strings = Arrays.asList("why", "hello", "there");

		// Then
		List<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匹配器中所有匹配器的项目?

@Test
	public void test_containsInAnyOrder_matchers() throws Exception {
		// Given
		List<String> strings = Arrays.asList("why", "hello", "there");

		// Then
		assertThat(strings, containsInAnyOrder(endsWith("llo"), equalTo("there"), startsWith("why")));
	}
3.1.10。 containsString()

如果被测字符串包含给定的子字符串,则匹配的匹配器。

@Test
	public void test_containsString() throws Exception {
		// Given
		String testValue = "value";

		// Then
		assertThat(testValue, containsString("alu"));
	}
3.1.11。 空()

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

@Test
	public void test_empty() throws Exception {
		// Given
		Set<String> testCollection = new HashSet<>();

		// Then
		assertThat(testCollection, is(empty()));
	}
3.1.12。 emptyArray()

如果输入数组的长度为0,则匹配的匹配器。

@Test
	public void test_emptyArray() throws Exception {
		// Given
		String[] testArray = new String[0];

		// Then
		assertThat(testArray, is(emptyArray()));
	}
3.1.13。 emptyCollectionOf()

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

@Test
	public void test_emptyCollectionOf() throws Exception {
		// Given
		Set<String> testCollection = new HashSet<>();

		// Then
		assertThat(testCollection, is(emptyCollectionOf(String.class)));
	}
3.1.14。 emptyIterable()

如果输入Iterable没有值,则匹配的匹配器。

@Test
	public void test_emptyIterable() throws Exception {
		// Given
		Set<String> testCollection = new HashSet<>();

		// Then
		assertThat(testCollection, is(emptyIterable()));
	}
3.1.15。 emptyIterableOf()

Typesafe Matcher,如果输入的Iterable没有值且为给定类型,则匹配。

@Test
	public void test_emptyIterableOf() throws Exception {
		// Given
		Set<String> testCollection = new HashSet<>();

		// Then
		assertThat(testCollection, is(emptyIterableOf(String.class)));
	}
3.1.16。 以。。结束()

如果输入String以给定的子字符串结尾,则匹配的匹配器。

@Test
	public void test_endsWith() throws Exception {
		// Given
		String testValue = "value";

		// Then
		assertThat(testValue, endsWith("lue"));
	}
3.1.17。 等于()

如果输入值在逻辑上等于给定测试值,则匹配的匹配器。 也可以在数组上使用,在这种情况下,它将检查数组的长度并确保输入测试数组中的所有值在逻辑上都等于指定数组的值。

单值。

@Test
	public void test_equalTo_value() throws Exception {
		// Given
		String testValue = "value";

		// Then
		assertThat(testValue, equalTo("value"));
	}

数组。

@Test
	public void test_equalTo_array() throws Exception {
		// Given
		String[] testValues = { "why", "hello", "there" };

		// Then
		String[] specifiedValues = { "why", "hello", "there" };
		assertThat(testValues, equalTo(specifiedValues));
	}
3.1.18。 equalToIgnoringCase()

如果输入的String值等于指定的String而忽略大小写,则匹配的匹配器。

@Test
	public void test_equalToIgnoringCase() throws Exception {
		// Given
		String testValue = "value";

		// Then
		assertThat(testValue, equalToIgnoringCase("VaLuE"));
	}
3.1.19。 equalToIgnoringWhiteSpace()

如果输入的String值等于指定的String而不匹配多余的空格,则匹配该匹配器。 忽略所有前导和尾随空格,并将所有剩余空格折叠为单个空格。

@Test
	public void test_equalToIgnoringWhiteSpace() throws Exception {
		// Given
		String testValue = "this    is   my    value    ";

		// Then
		assertThat(testValue, equalToIgnoringWhiteSpace("this is my value"));
	}
3.1.20。 eventFrom()

如果输入EventObject来自给定Source,则匹配的Matcher。 也可以接受指定子类型的EventObeject

@Test
	public void test_eventFrom() throws Exception {
		// Given
		Object source = new Object();
		EventObject testEvent = new EventObject(source);

		// Then
		assertThat(testEvent, is(eventFrom(source)));
	}

指定子类型。

@Test
	public void test_eventFrom_type() throws Exception {
		// Given
		Object source = new Object();
		EventObject testEvent = new MenuEvent(source);

		// Then
		assertThat(testEvent, is(eventFrom(MenuEvent.class, source)));
	}
3.1.21。 比...更棒()

如果输入测试值大于指定值,则匹配的匹配器。

@Test
	public void test_greaterThan() throws Exception {
		// Given
		Integer testValue = 5;

		// Then
		assertThat(testValue, is(greaterThan(3)));
	}
3.1.22。 GreaterThanOrEqual()

如果输入测试值大于或等于指定值,则匹配的匹配器。

@Test
	public void test_greaterThanOrEqualTo() throws Exception {
		// Given
		Integer testValue = 3;

		// Then
		assertThat(testValue, is(greaterThanOrEqualTo(3)));
	}
3.1.23。 hasEntry()

如果给定映射包含与指定键和值匹配的条目,则匹配器或匹配器。

实际值

@Test
	public void test_hasEntry() throws Exception {
		// Given
		Integer testKey = 1;
		String testValue = "one";
		
		Map<Integer, String> testMap = new HashMap<>();
		testMap.put(testKey, testValue);

		// Then
		assertThat(testMap, hasEntry(1, "one"));
	}

匹配器

@Test
	public void test_hasEntry_matchers() throws Exception {
		// Given
		Integer testKey = 2;
		String testValue = "two";
		
		Map<Integer, String> testMap = new HashMap<>();
		testMap.put(testKey, testValue);

		// Then
		assertThat(testMap, hasEntry(greaterThan(1), endsWith("o")));
	}
3.1.24。 hasItem()

如果输入Iterable具有至少一项与指定值或匹配器匹配的项,则匹配器。

实际价值

@Test
	public void test_hasItem() throws Exception {
		// Given
		List<Integer> testList = Arrays.asList(1,2,7,5,4,8);

		// Then
		assertThat(testList, hasItem(4));
	}

匹配器

@Test
	public void test_hasItem_matcher() throws Exception {
		// Given
		List<Integer> testList = Arrays.asList(1,2,7,5,4,8);

		// Then
		assertThat(testList, hasItem(is(greaterThan(6))));
	}
3.1.25。 hasItemInArray()

如果输入数组具有至少一个与指定值或匹配器匹配的项目,则匹配的匹配器。

实际价值

@Test
	public void test_hasItemInArray() throws Exception {
		// Given
		Integer[] test = {1,2,7,5,4,8};

		// Then
		assertThat(test, hasItemInArray(4));
	}

匹配器

@Test
	public void test_hasItemInArray_matcher() throws Exception {
		// Given
		Integer[] test = {1,2,7,5,4,8};

		// Then
		assertThat(test, hasItemInArray(is(greaterThan(6))));
	}
3.1.26。 hasItems()

如果输入Iterable具有任意顺序的所有指定值或匹配器,则匹配的匹配器。

实际值

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

		// Then
		assertThat(testList, hasItems(4, 2, 5));
	}

匹配器

@Test
	public void test_hasItems_matcher() throws Exception {
		// Given
		List<Integer> testList = Arrays.asList(1,2,7,5,4,8);

		// Then
		assertThat(testList, hasItems(greaterThan(6), lessThan(2)));
	}
3.1.27。 hasKey()

如果输入Map具有至少一个与指定值或匹配项匹配的键,则匹配的匹配项。

实际价值

@Test
	public void test_hasKey() throws Exception {
		// Given
		Map<String, String> testMap = new HashMap<>();
		testMap.put("hello", "there");
		testMap.put("how", "are you?");

		// Then
		assertThat(testMap, hasKey("hello"));
	}

匹配器

@Test
	public void test_hasKey_matcher() throws Exception {
		// Given
		Map<String, String> testMap = new HashMap<>();
		testMap.put("hello", "there");
		testMap.put("how", "are you?");

		// Then
		assertThat(testMap, hasKey(startsWith("h")));
	}
3.1.28。 hasProperty()

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

物业名称

@Test
	public void test_hasProperty() throws Exception {
		// Given
		JTextField testBean = new JTextField();
		testBean.setText("Hello, World!");

		// Then
		assertThat(testBean, hasProperty("text"));
	}

属性名称和值匹配器

@Test
	public void test_hasProperty_value() throws Exception {
		// Given
		JTextField testBean = new JTextField();
		testBean.setText("Hello, World!");

		// Then
		assertThat(testBean, hasProperty("text", startsWith("H")));
	}
3.1.29。 hasSize()

如果输入Collection具有指定的大小,或者它的大小与指定的匹配器匹配,则匹配器。
实际价值

@Test
	public void test_hasSize() throws Exception {
		// Given
		List<Integer> testList = Arrays.asList(1,2,3,4,5);

		// Then
		assertThat(testList, hasSize(5));
	}

匹配器

@Test
	public void test_hasSize_matcher() throws Exception {
		// Given
		List<Integer> testList = Arrays.asList(1,2,3,4,5);

		// Then
		assertThat(testList, hasSize(lessThan(10)));
	}
3.1.30。 hasToString()

如果输入对象的toString()方法匹配指定的String或输入匹配器,则匹配的匹配器。

正常价值

@Test
	public void test_hasToString() throws Exception {
		// Given
		Integer testValue = 4;

		// Then
		assertThat(testValue, hasToString("4"));
	}

匹配器

@Test
	public void test_hasToString_matcher() throws Exception {
		// Given
		Double testValue = 3.14;

		// Then
		assertThat(testValue, hasToString(containsString(".")));
	}
3.1.31。 hasValue()

如果输入Map具有至少一个与指定值或匹配器匹配的值,则匹配的匹配器。

实际价值

@Test
	public void test_hasValue() throws Exception {
		// Given
		Map<String, String> testMap = new HashMap<>();
		testMap.put("hello", "there");
		testMap.put("how", "are you?");

		// Then
		assertThat(testMap, hasValue("there"));
	}

匹配器

@Test
	public void test_hasValue_matcher() throws Exception {
		// Given
		Map<String, String> testMap = new HashMap<>();
		testMap.put("hello", "there");
		testMap.put("how", "are you?");

		// Then
		assertThat(testMap, hasValue(containsString("?")));
	}
3.1.32。 hasXPath()

如果输入XML DOM节点满足输入XPath表达式,则匹配的匹配器。

节点是否包含与输入XPath表达式匹配的节点?

@Test
	public void test_hasXPath() throws Exception {
		// Given
		DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Node testNode = docBuilder.parse(
		        new InputSource(new StringReader("<xml><top><middle><bottom>value</bottom></middle></top></xml>")))
		        .getDocumentElement();

		// Then
		assertThat(testNode, hasXPath("/xml/top/middle/bottom"));
	}

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

@Test
	public void test_hasXPath_matcher() throws Exception {
		// Given
		DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Node testNode = docBuilder.parse(
		        new InputSource(new StringReader("<xml><top><middle><bottom>value</bottom></middle></top></xml>")))
		        .getDocumentElement();

		// Then
		assertThat(testNode, hasXPath("/xml/top/middle/bottom", startsWith("val")));
	}

节点是否在指定的名称空间中包含与输入XPath表达式匹配的节点?

@Test
public void test_hasXPath_namespace() throws Exception {
   // Given
   DocumentBuilderFactory 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;
       }
   };

   // Then
   assertThat(testNode, hasXPath("//prefix:bottom", namespace));
}

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

@Test
public void test_hasXPath_namespace_matcher() throws Exception {
  // Given
  DocumentBuilderFactory 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;
     }
  };

  // Then
  assertThat(testNode, hasXPath("//prefix:bottom", namespace, startsWith("val")));
}
3.1.33。 instanceOf()

如果输入对象是给定类型,则匹配器。

@Test
public void test_instanceOf() throws Exception {
  // Given
  Object string = "Hello, World!";

  // Then
  assertThat(string, instanceOf(String.class));
}
3.1.34。 isEmptyOrNullString()

当输入字符串为空或null时匹配的匹配器。

@Test
public void test_isEmptyOrNullString() throws Exception {
  // Given
  String emptyString = ";
  String nullString = null;

  // Then
  assertThat(emptyString, isEmptyOrNullString());
  assertThat(nullString, isEmptyOrNullString());
}
3.1.35。 isEmptyString()

当输入字符串为空时匹配的匹配器。

@Test
public void test_isEmptyString() throws Exception {
  // Given
  String emptyString = ";

  // Then
  assertThat(emptyString, isEmptyString());
}
3.1.36。 isIn()

当在给定的Collection或Array中找到输入项时匹配的匹配器。

@Test
public void test_isIn() throws Exception {
  // Given
  Set<Integer> set = new HashSet<>();
  set.add(3);
  set.add(6);
  set.add(4);

  // Then
  assertThat(4, isIn(set));
}
3.1.37。 是其中之一()

当输入对象是给定对象之一时匹配的匹配器。

@Test
public void test_isOneOf() throws Exception {
  // Then
  assertThat(4, isOneOf(3,4,5));
}
3.1.38。 iterableWithSize()

当输入Iterable具有指定大小时匹配或与指定大小匹配器匹配的匹配器。

实际价值

@Test
public void test_iterableWithSize() throws Exception {
  // Given
  Set<Integer> set = new HashSet<>();
  set.add(3);
  set.add(6);
  set.add(4);

  // Then
  assertThat(set, iterableWithSize(3));
}

匹配器

@Test
public void test_iterableWithSize_matcher() throws Exception {
  // Given
  Set<Integer> set = new HashSet<>();
  set.add(3);
  set.add(6);
  set.add(4);

  // Then
  assertThat(set, iterableWithSize(lessThan(4)));
}
3.1.39。 少于()

匹配器,使用compareTo方法匹配输入对象小于指定值的可比较对象。

@Test
public void test_lessThan() throws Exception {
  // Then
  assertThat("apple", lessThan("zoo"));
}
3.1.40。 lessThanOrEqualTo()

匹配器,使用compareTo方法匹配输入对象小于或等于指定值的可比较对象。

@Test
public void test_lessThanOrEqualTo() throws Exception {
   // Then
   assertThat(2, lessThanOrEqualTo(2));
}
3.1.41。 不()

包裹现有匹配器并反转其匹配逻辑的匹配器

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

当与值而不是匹配器一起使用时,也是not(equalTo(...))的别名

@Test
public void test_not_value() throws Exception {
   // Then
   assertThat("apple", not("orange"));
}
3.1.42。 notNullValue()

当输入值不为null时匹配的匹配器。

@Test
public void test_notNullValue() throws Exception {
   // Then
   assertThat("apple", notNullValue());
}
3.1.43。 nullValue()

当输入值为null时匹配的匹配器。

@Test
public void test_nullValue() throws Exception {
   // Given
   Object nothing = null;
  
   // Then
   assertThat(nothing, nullValue());
}
3.1.44。 sameInstance()

当输入对象与指定值相同的实例时匹配的匹配器。

@Test
public void test_sameInstance() throws Exception {
   // Given
   Object one = new Object();
   Object two = one;

   // Then
   assertThat(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;
    }
}

我们可以编写以下测试:

@Test
    public void test_samePropertyValuesAs() throws Exception {
        // Given
        Bean one = new Bean();
        one.setText("text");
        one.setNumber(3);

        Bean two = new Bean();
        two.setText("text");
        two.setNumber(3);

        // Then
        assertThat(one, samePropertyValuesAs(two));
    }
3.1.46。 以。。开始()

如果输入字符串以给定前缀开头的匹配项。

@Test
    public void test_startsWith() throws Exception {
        // Given
        String test = "Beginnings are important!";

        // Then
        assertThat(test, startsWith("Beginning"));
    }
3.1.47。 stringContainsInOrder()

匹配器,如果输入的String包含给定的Iterable中的子字符串,则按从Iterable返回的顺序进行匹配。

@Test
    public void test_stringContainsInOrder() throws Exception {
        // Given
        String test = "Rule number one: two's company, but three's a crowd!";

        // Then
        assertThat(test, stringContainsInOrder(Arrays.asList("one", "two", "three")));
    }
3.1.48。 theInstance()

当输入对象与指定值相同的实例时匹配的匹配器。 行为与“ sameInstance()”相同

@Test
public void test_theInstance() throws Exception {
   // Given
   Object one = new Object();
   Object two = one;

   // Then
   assertThat(one, theInstance(two));
}
3.1.49。 typeCompatibleWith()

当输入类型的对象可以分配给指定基本类型的引用时匹配的匹配器。

@Test
    public void test_typeCompatibleWith() throws Exception {
        // Given
        Integer integer = 3;

        // Then
        assertThat(integer.getClass(), typeCompatibleWith(Number.class));
    }

简单匹配器结合其他匹配器

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

3.2.1。 所有的()

当所有输入Matchers都匹配时匹配的Matcher的行为类似于逻辑AND。 可以使用单个Matchers或Iterable Matchers。

个人匹配器

@Test
    public void test_allOf_individual() throws Exception {
        // Given
        String test = "starting off well, gives content meaning, in the end";

        // Then
        assertThat(test, allOf(startsWith("start"), containsString("content"), endsWith("end")));
    }

匹配器的迭代

@Test
    public void test_allOf_iterable() throws Exception {
        // Given
        String test = "Hello, world!";

        List<Matcher<? super String>> matchers = Arrays.asList(containsString("world"), startsWith("Hello"));

        // Then
        assertThat(test, allOf(matchers));
    }
3.2.2。 任何()

当任何输入匹配器匹配时匹配的匹配器,其行为类似于逻辑或。 可以使用单个Matchers或Iterable Matchers。

个人匹配器

@Test
    public void test_anyOf_individual() throws Exception {
        // Given
        String test = "Some things are present, some things are not!";

        // Then
        assertThat(test, anyOf(containsString("present"), containsString("missing")));
    }

匹配器的迭代

@Test
    public void test_anyOf_iterable() throws Exception {
        // Given
        String test = "Hello, world!";

        List<Matcher<? super String>> matchers = Arrays.asList(containsString("Hello"), containsString("Earth"));

        // Then
        assertThat(test, anyOf(matchers));
    }
3.2.3。 array()

当输入数组的元素分别使用指定的Matchers依次进行匹配时匹配的Matcher。 匹配器的数量必须等于数组的大小。

@Test
    public void test_array() throws Exception {
        // Given
        String[] test = {"To be", "or not to be", "that is the question!"};

        // Then
        assertThat(test, array(startsWith("To"), containsString("not"), instanceOf(String.class)));
    }
3.2.4。 都()

匹配器,当与它的可组合匹配器.and()结合使用时,将在两个指定匹配器匹配时匹配。

@Test
    public void test_both() throws Exception {
        // Given
        String test = "Hello, world!";

        // Then
        assertThat(test, both(startsWith("Hello")).and(endsWith("world!")));
    }
3.2.5。 要么()

匹配器,当与它的可组合匹配器.or()结合使用时,如果指定的匹配器匹配,则匹配器。

@Test
    public void test_either() throws Exception {
        // Given
        String test = "Hello, world!";

        // Then
        assertThat(test, either(startsWith("Hello")).or(endsWith("universe!")));
    }
3.2.6。 is()

当输入匹配器匹配时匹配的匹配器,只是为了方便起见,使断言更像英语。

@Test
    public void test_is_matcher() throws Exception {
        // Given
        Integer test = 5;

        // Then
        assertThat(test, is(greaterThan(3)));
    }

也用作is(equalTo(...))的别名,类似于not(...)not(equalTo(...))

@Test
    public void test_is_value() throws Exception {
        // Given
        Integer test = 5;

        // Then
        assertThat(test, is(5));
    }
3.2.7。 被描述成()

匹配器,用于覆盖另一个匹配器的失败输出。 在需要自定义故障输出时使用。 参数是失败消息,原始Matcher,然后是将使用占位符%0,%1,%2格式化为失败消息的任何值。

@Test
    public void test_describedAs() throws Exception {
        // Given
        Integer actual = 7;
        Integer expected = 10;

        // Then
        assertThat(actual, describedAs("input > %0", greaterThan(expected), expected));
    }

4。结论

现在,我们访问了Hamcrest中定义的所有Matchers,并看到了每个匹配器的实例。 库中有很多非常有用且功能强大的Matchers,尤其是当彼此结合使用时。 但是有时候我们需要做的比现有的还要多。 在下一个教程中,我们将研究如何创建自己的自定义Matchers,以扩展Hamcrest并使它更加有用!

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

matchers依赖

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值