Hamcrest equalTo () Matcher

Introducing Hamcrest`s equalTo Matcher.

equalTo is a Matcher that checks if a string is equal, or if a Collection component such as an Array or List is equal.

Set project dependencies

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

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

String

You can test for equality of String objects like this:

@Test
public void testStringsEquals() {
    String str1 = "equals";
    String str2 = "equals";

    assertThat(str1, equalTo(str2));
}

Because it is case-sensitive, in the next test two strings are counted as having the same alphabet but not the same object.

@Test
public void testStringsEquals2() {
    String str1 = "equals";
    String str2 = "EQUALS";

    assertThat(str1, not(equalTo(str2)));
}

Array

Comparisons of array objects can be tested like this:

@Test
public void testArrayEquals() {
    String[] arr1 = new String[] {"a", "b", "c"};
    String[] arr2 = new String[] {"a", "b", "c"};

    assertThat(arr1, equalTo(arr2));
}

Since the data location (Index) stored in the array is also compared, it is determined that the two objects are not the same in the next test.

@Test
public void testArrayEquals2() {
    String[] arr1 = new String[] {"a", "b", "c"};
    String[] arr2 = new String[] {"c", "b", "a"};

    assertThat(arr1, not(equalTo(arr2)));
}

List

Lists are the same as arrays. The index of the stored data is divided and compared.

@Test
public void testListEquals() {
    List<String> list1 = Arrays.asList("a", "b");
    List<String> list2 = Arrays.asList("a", "b");

    assertThat(list1, equalTo(list2));
}

Therefore, in the next test, the two objects are judged to be different.

@Test
public void testListEquals2() {
    List<String> list1 = Arrays.asList("a", "b");
    List<String> list2 = Arrays.asList("b", "a");

    assertThat(list1, not(equalTo(list2)));
}

Set

A Set is an unordered Collection of data. Thus, the two objects in the test below are counted as equal.

@Test
public void testSetEquals() {
    Set<String> set1 = new HashSet<>(Arrays.asList("a", "b"));
    Set<String> set2 = new HashSet<>(Arrays.asList("b", "a"));

    assertThat(set1, equalTo(set2));
}

If the components of an object are different, they are counted as unequal, as shown below.

@Test
public void testSetEquals2() {
    Set<String> set1 = new HashSet<>(Arrays.asList("a", "b"));
    Set<String> set2 = new HashSet<>(Arrays.asList("b"));

    assertThat(set1, not(equalTo(set2)));
}

Map

Map is also an unordered Collection. The two objects in the test below are considered equal.

@Test
public void testMapEquals() {
    Map<String, Object> map1 = Map.of(
            "a", "123",
            "b", "456"
    );
    Map<String, Object> map2 = Map.of(
            "b", "456",
            "a", "123"
    );

    assertThat(map1, equalTo(map2));
}
codechachaCopyright ©2019 codechacha