← Back to libraryQuestion 238 of 468
🔌REST AssuredIntermediate

Hamcrest Matchers for Assertions

📌 Definition:

REST Assured validations use Hamcrest matchers (equalTo, hasItems, containsString, greaterThan, notNullValue, etc.) to express readable, expressive assertions on response values.

📖 Detailed Explanation:

Common matchers: equalTo(x) for equality; not(equalTo(x)); hasItem(x)/hasItems(a, b) for collection membership; containsString(s) for substrings; greaterThan/lessThan for numbers; hasKey/hasEntry for maps; notNullValue()/nullValue(); is(...) as a readable wrapper; and oneOf(...) for a set of allowed values. You combine them (allOf, anyOf) and use them in body()/header()/time(). Because matchers produce clear failure messages (expected X but was Y), they make API assertions self-explanatory. They come from org.hamcrest.Matchers via static import.

🔑 Key Points:
  • equalTo, hasItem(s), containsString, greaterThan/lessThan, notNullValue
  • Combine with allOf/anyOf/not; is() for readability
  • oneOf() allows a set of acceptable values
  • Static import org.hamcrest.Matchers.*
🌍 Real-World Example:

Flexible validation: then().body('roles', hasItems('qa', 'admin')).body('age', greaterThan(18)).body('token', notNullValue()) — asserting membership, a numeric bound, and presence in one chain.

🎯 Scenario-Based Interview Question:

You want to assert a status code is EITHER 200 or 201. What's the clean matcher-based way?