Mixing Hamcrest and TestNG

Robert Munteanu picture Robert Munteanu · Jul 7, 2009 · Viewed 13.8k times · Source

Has anyone integrated Hamcrest with TestNG so that its matchers can easily be used in TestNG assertions?

Answer

kevinarpe picture kevinarpe · May 11, 2013

In short, to answer your question: You don't need to integrate TestNG with Hamcrest. Just call org.hamcrest.MatcherAssert.assertThat(...) directly which throws java.lang.AssertionError.

Background

I found your question via Google, wondering exactly the same issue. After further Googling, I didn't find any satisfying answers, so I read the source code for JUnit's integration with Hamcrest.

With JUnit, Hamcrest integration is normally used by calling:

org.junit.Assert.assertThat(
    T actual,
    org.hamcrest.Matcher<? super T> matcher)

When I read the source code, I discovered it just a small wrapper to call:

org.hamcrest.MatcherAssert.assertThat(
    String reason,
    T actual,
    org.hamcest.Matcher<? super T> matcher)

This function throws java.lang.AssertionError.