Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing Hamcrest and TestNG

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

like image 232
Robert Munteanu Avatar asked Jul 07 '09 15:07

Robert Munteanu


People also ask

Can we use Hamcrest with TestNG?

This is great except that TestNG has soft assertions which can't be used from Hamcrest.

Why we use TestNG instead of Hamcrest?

Hamcrest vs TestNG TestNG is a testing framework, and as noted above, Hamcrest is a matcher framework. Both frameworks allow us to make assertions; it is here where Hamcrest does a better job than TestNG. TestNG is a testing framework, and as noted above, Hamcrest is a matcher framework.

Is assertThat actual is Equalto expected a valid Hamcrest Assert statement?

assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.

Is Hamcrest a matcher?

Introduction. Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluable, such as UI validation or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.


1 Answers

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.

like image 197
kevinarpe Avatar answered Sep 30 '22 15:09

kevinarpe