Using Hamcrest with TestNG

By xngo on February 21, 2019

Overview

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 org.hamcrest.Matchers.is;
 
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")));
    }
}

Output

Results of Hamcrest with TestNG

Github

  • https://github.com/xuanngo2001/java-testng/blob/master/src/net/openwritings/testng/HamcrestInTestNG.java

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.
  • http://www.objectpartners.com/2013/09/18/the-benefits-of-using-assertthat-over-other-assert-methods-in-unit-tests/

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.