JUnit with Hamcrest

Q1. What is Hamcrest, and what is its purpose?
A1. HAMCREST is an anagram for MATCHER. The purpose is to match the assertions the BDD (Behavior Driven Development) style. In short, reads better like English statements. So,

Instead of:

with Hamcrest, reads better

where “is(…)” needs a static import of

The above reads like English: assertThat “actual value” is equalTo “expected value”.

Q2. What are the CoreMatchers class methods available for assertions?
A2. The CoreMatchers class has methods like

  • allOf()
  • any()
  • anyOf()
  • anything()
  • describedAs()
  • equalTo()
  • instanceOf()
  • is()
  • not()
  • notNullValue()
  • nullValue()
  • sameInstance()

Q3. What is the purpose of “assertThat” method in org.junit.Assert class?
A3. It replaces the deprecated org.junit.Assert.assertEquals() method, and it has the signature of

Examples with Hamcrest

800+ Java & Big Data Interview Q&As