Using Hamcrest

By xngo on June 10, 2019


Hamcrest is a framework that allows you to use its matchers to check for different conditions. These matchers happen to be very useful in doing unit tests. Besides, Hamcrest has the goal to make its matchers as readable as possible. For examples,

assertThat(actual, is(equalTo(expected)));
assertThat(actual, is(not(equalTo(expected))));
assertThat("test", anyOf(is("testing"), containsString("est")));


  1. Download the latest JAR version of Hamcrest(e.g. hamcrest-2.1.jar) from
  2. Add the JAR file to your library class path.

Here is a video showing how to add Hamcrest in Eclipse.

Setup Hamcrest in Eclipse


import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
public class UsingHamcrest {
    public static void main(String[] args) {
        String str="Xuan";
        // Examples in matching context.
        // Positive match.
        if( equalTo("Xuan").matches(str) )
            System.out.println("The string is equal to Xuan.");
            System.out.println("The string is NOT equal to Xuan.");
        // Negative match.
        str = "Some very long string.";
        if( containsString("Xuan").matches(str) )
            System.out.println("String does contain 'Xuan'.");
            System.out.println("String does NOT contain 'Xuan'.");
        // Examples in unit test context.
        // Exception thrown.
        str = "Assert string containing something.";
        assertThat(str, is(equalTo("Not found")));


Output of Hamcrest examples




  • List of all matchers that you can use: allOf(), any(), anyOf(), anything(), both(), containsString(), describedAs(), either(), endsWith(), equalTo(), everyItem(), hasItems(), instanceOf(), is(), isA(), not(), notNullValue(), nullValue(), sameInstance(), startsWith(), theInstance(), etc.

About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.