Using Hamcrest with TestNG

By xngo on February 21, 2019


Hamcrest is a set of matchers that allows you to create flexible expression to check for your conditions. They are a perfect fit with a unit test framework such as TestNG. They will make your validation expression much more easy to read. For examples,

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

Examples of Hamcrest with TestNG

The code example below will show 1 failed test and 1 successful test.

package net.openwritings.testng;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static;
import org.testng.annotations.Test;
public class HamcrestInTestNG
    @Test(description="Negative test containsString().")
    public void containsStringNegativeTest(){
        String actual = "Assert string containing something.";
        assertThat(actual, containsString("Not found"));
    @Test(description="Positive test is().")
    public void isPositiveTest(){
        String actual = "Xuan";
        assertThat(actual, is(equalTo("Xuan")));


Results of Hamcrest with TestNG




  • 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.