Hamcrest Matchers – All Tactics are Here!

Hamcrest is a library of matchers, is an external add-on of the Junit Framework. How to add hamcrest methods into your project by IntelliJ as shown below.

For example, we are writing a JUnit test with hamcrest “Is” method. First, click “assertThat” and then press alt+Enter then click “Static Import Method…

junit_9

Then, select which library you want. I chose org.hamcrest

junit_10

Then click “is” and press alt+enter and select “Static Import Method…

junit_11

Then, select “Is.is(org.hamcrest.core) method and import related hamcrest method.

junit_12

You can import all Hamcrest methods in this way.

If you want to download all of the matchers into your project, you should add the source .jar files or you should add Hamcrest maven dependency.

Java sources and maven dependency descriptions can be found in this link https://mvnrepository.com/artifact/org.hamcrest/hamcrest-all and a sample maven dependency is shown below.

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

In this tutorial, I will explain and show examples of core hamcrest methods. If you want to learn much more about hamcrest, you can find all detailed information in the Hamcrest documentation link http://hamcrest.org/

Matchers are used with the org.junit.Assert.assertThat() method. You can find their descriptions and examples in the below table.

Matcher Description & Example
AllOf

Calculates the logical conjunction of multiple matchers. Examined object must match ALL of the specified matcher.

Example
assertThat(“myString”, allOf(startsWith(“my”), containsString(“Str”)))

AnyOf

Calculates the logical disjunction of multiple matchers. Examined object matches ANY of the specified matchers.

Example
assertThat(“myString”, allOf(startsWith(“your”), containsString(“Str”)))

DescribedAs

Adds a description to a Matcher

Example
assertThat(“Sunday”, describedAs(“Sunday is not Saturday.”, is(not(“Saturday”))));

Is

Decorates another Matcher, retaining its behavior. In other words it checks given objects equality. Is method allows tests to be more meaningful/expressive.

Example
assertThat(cheese, is(equalTo(smelly)))
instead of:
assertThat(cheese, equalTo(smelly))

IsAnything

A matcher that always returns true.

Example
assertThat(“Onur”, is(anything(“Bla Bla Bla”)));

IsEqual

It checks given objects equality.

Example
assertThat("str", equalTo("str "));
or
assertThat("str ", is(equalTo("str ")));

IsInstanceOf 

Tests whether the value is an instance of a class.

Example
assertThat(myInstanceTest, instanceOf(InstanceTest.class));

IsNot<T>  Creates a matcher that wraps an existing matcher, but inverts the logic by which it will match.

Example
assertThat(“onur”, is(not(equalTo(“mike”))));
IsNull<T>

Checks whether value is null

Example
assertThat(myStr, is(nullValue()));

 IsSame<T>

Creates a matcher that matches only when the examined object is the same instance as the specified target object.

Example
assertThat(str1, IsSame.<String>sameInstance(str2));

In the below code, you can find the usage of all matchers. I also tried to emphasize their descriptions with inline comments.

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import org.hamcrest.core.IsSame;
import org.junit.jupiter.api.Test;

public class hamcrestTest {

    //is method checks two values are equal or not.
    //If they are equal it returns true!
    //Below test will pass!
    @Test
    public void isMatcherTest() {
        assertThat("Onur", is("Onur"));
        assertThat(34, is(34));
    }

    //------------------------------------------------------------

    //IsNot method checks two values are equal or not.
    //If they are not equal it returns true!
    //Below test will pass!
    @Test
    public void isnotMatcherTest() {
        assertThat("Onur", is(not("Mike")));
    }

    //------------------------------------------------------------

    //AllOf method creates a matcher that matches
    //if the examined object matches ALL of the specified matchers.
    //Below test will pass!
    @Test
    public void allOfMatcherTest() {
        assertThat("myValue", allOf(startsWith("my"), containsString("Val")));
    }

    //------------------------------------------------------------

    //AnyOf method creates a matcher that matches
    //if the examined object matches ANY of the specified matchers.
    //Below test will pass!
    @Test
    public void anyOfMatcherTest() {
        assertThat("myValue", anyOf(startsWith("your"), containsString("Val")));
    }

    //------------------------------------------------------------

    //describedAs method adds a description to a Matcher
    //Below test will pass!
    @Test
    public void describedAsMatcherTest() {
        assertThat("Sunday", describedAs("Sunday is not Saturday.", is(not("Saturday"))));
    }

    //------------------------------------------------------------

    //IsAnything method is a matcher that always returns true.
    //Below test will pass!
    @Test
    public void isAnythingMatcherTest() {
        assertThat("Onur", is(anything("Bla Bla Bla")));
    }

    //------------------------------------------------------------

    //IsEqual method checks given objects equality.
    //Below test will pass!
    @Test
    public void isEqualMatcherTest() {
        assertThat("str", equalTo("str"));
        assertThat("str", is(equalTo("str")));
    }

    //------------------------------------------------------------

    //IsInstanceOf method creates a matcher that matches when the examined object is an instance of the specified type,
    //as determined by calling the Class.isInstance(Object) method on that type, passing the the examined object.
    //Below test will pass!
    InstanceTest myInstanceTest = new InstanceTest();

    @Test
    public void isInstanceOfMatcherTest() {
        assertThat(myInstanceTest, instanceOf(InstanceTest.class));
    }

    //------------------------------------------------------------

    //IsNot method creates a matcher that wraps an existing matcher, but inverts the logic by which it will match.
    //Below test will pass!
    @Test
    public void isNotMatcherTest() {
        assertThat("onur", is(not(equalTo("mike"))));
    }

    //------------------------------------------------------------

    //IsNull creates a matcher that matches if examined object is null.
    //Below test will pass!
    String myStr  = null;
    String myStr2 = "Onur";

    @Test
    public void isNullMatcherTest() {
        assertThat(myStr, is(nullValue()));
        assertThat(myStr2, is(notNullValue()));
    }

    //IsSame method creates a matcher that matches only when the
    //examined object is the same instance as the specified target object.
    //Below test will pass!
    @Test
    public void isSameMatcherTest() {
        String str1 = "Onur";
        String str2 = "Onur";

        assertThat(str1, IsSame.sameInstance(str2));
    }
}

class InstanceTest {
    String str = "Hello World!\n";

    public void print_1(String str) {
        System.out.println(str);
    }
}

You can also check nice examples of hamcrest matchers in here: https://github.com/leveluplunch/levelup-java-examples/blob/master/src/test/java/com/levelup/java/hamcrest/CoreMatchers.java

GitHub

https://github.com/swtestacademy/junit/tree/hamcrest

Summary

  • You learned how to use and the meanings of hamcrest matchers.
  • You practiced with hamcrest matchers examples.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.