Using Hamcrest

By xngo on June 10, 2019

Overview

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")));

Installation

  1. Download the latest JAR version of Hamcrest(e.g. hamcrest-2.1.jar) from https://mvnrepository.com/artifact/org.hamcrest/hamcrest.
  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

Examples

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.
        str="Xuan";
        if( equalTo("Xuan").matches(str) )
            System.out.println("The string is equal to Xuan.");
        else
            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'.");
        else
            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

Output of Hamcrest examples

Github

  • https://github.com/xuanngo2001/java-hamcrest

Reference

  • 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 OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.