Hamcrest Collections Matcher

Introduces Matchers that check the data of Collections such as List.

Set project dependencies

Gradle project adds java-hamcrest as below in java-hamcrest.

dependencies {
    testImplementation 'org.hamcrest:java-hamcrest:2.0.0.0'
}

hasItem()

hasItem is a Matcher that checks which items the Collections have.

This can be used to check what values a list has, like this:

@Test
public void testCollectionHasItem() {
    List<String> list = Arrays.asList("a", "b", "c");

    assertThat(list, hasItem("a"));
    assertThat(list, not(hasItem("d")));
}

hasItems()

You can use hasItems when checking multiple items together instead of one. The order in which they are passed as arguments to hasItems does not matter. If the passed-in items are all in the list, Matcher returns true.

@Test
public void testCollectionHasItems() {
    List<String> list = Arrays.asList("a", "b", "c");

    assertThat(list, hasItems("c", "a"));
    assertThat(list, hasItems("a", "b", "c"));
}

containsInAnyOrder()

containsInAnyOrder, same as hasItems, is a Matcher used to check the number of items a list has.

@Test
public void testArrayContainsInAnyOrder() {
    List<String> list = Arrays.asList("a", "b", "c");

    assertThat(list, containsInAnyOrder("c", "b", "a"));
}

contains()

If you also need to compare the order of items stored in the list, you can use contains(). contains returns false when the order is different.

@Test
public void testCollectionContains() {
    List<String> list = Arrays.asList("a", "b", "c");

    assertThat(list, contains("a", "b", "c"));
    assertThat(list, not(contains("c", "b", "a")));
}

empty()

You can use empty() to check if Collections such as List, Set, etc. are empty.

List<String> list = Collections.emptyList();
assertThat(list, empty());

Set<String> set = new HashSet<>();
assertThat(set, empty());

In the case of Map, you can check for empty as follows.

Map<String, String> map = new HashMap();
assertThat(map, anEmptyMap());
codechachaCopyright ©2019 codechacha