Hamcrest Text Matcher

Learn about string matchers provided by Hamcrest.

Set project dependencies

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

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

Equality

equalTo() is a Matcher that checks if two strings are equal. When comparing strings, it is case-sensitive.

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

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

If you want to compare case insensitively you can use equalToIgnoringCase().

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

    assertThat(str1, equalToIgnoringCase(str2));
}

You can also use equalToIgnoringWhiteSpace() if you want to ignore case-insensitive whitespace before and after strings.

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

    assertThat(str1, equalToIgnoringWhiteSpace(str2));
}

Empty

emptyString() is a Matcher that checks if a string is empty. If you want to check both null and empty, you can use emptyOrNullString().

@Test
public void testStringsEmpty() {
    String emptyStr = "";
    String nullStr = null;

    assertThat(emptyStr, emptyString());
    assertThat(nullStr, emptyOrNullString());
}

string comparison

Regex Pattern

When comparing strings, you can compare them with regular expressions. matchesPattern() is a Matcher that checks if a string matches the regular expression passed as an argument.

@Test
public void testStringsPattern() {
    String str = "String Pattern Matchers";

    assertThat(str, matchesPattern("String.*Matchers"));
}

Contains

containsString() is a Matcher that checks if a string contains a specific string. If you dont want to be case sensitive, you can use containsStringIgnoringCase()`.

@Test
public void testStringsContains() {
    String str = "String Pattern Matchers";

    assertThat(str, containsString("Matchers"));
    assertThat(str, containsStringIgnoringCase("pattern"));
}

StartsWith

You can use startsWith() to check if a string starts with a specific string, or startsWithIgnoringCase() if you don`t need case sensitivity.

@Test
public void testStringsStartsWith() {
    String str = "String Pattern Matchers";

    assertThat(str, startsWith("String"));
    assertThat(str, startsWithIgnoringCase("string"));
}

EndsWith

You can use endsWith() to check if a string ends with a specific string, or endsWithIgnoringCase() if you don`t need case sensitivity.

@Test
public void testStringsEndsWith() {
    String str = "String Pattern Matchers";

    assertThat(str, endsWith("Matchers"));
    assertThat(str, endsWithIgnoringCase("matchers"));
}
codechachaCopyright ©2019 codechacha