π― Declarative Assertion Architecture & Matcher Composition
While primitive equality checks (assertEquals) confirm static scalar values, enterprise JSON payloads demand sophisticated, pattern-based validation across arrays, maps, floating-point metrics, and partial strings. Hamcrest is the declarative matcher library bundled natively into REST Assured's BDD pipeline via org.hamcrest.Matchers.*. Rather than extracting values into local variables and writing nested Java loops, null-checks, and regex evaluators, Hamcrest enables engineers to state what conditions the payload must satisfy directly inside the .body("path", matcher) pipeline. From verifying unordered collection membership via containsInAnyOrder() and partial subset inclusion via hasItems(), to enforcing composite logical constraints with allOf() and anyOf(), Hamcrest produces detailed, self-documenting diagnostic failure traces that pinpoint exact data mismatches without additional debugging overhead.
Matcher<T> interface and integrate into REST Assured's GPath evaluation pipeline.
HAMCREST MATCHER ARCHITECTURE & EVALUATION SURFACE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BASE INTERFACE: org.hamcrest.Matcher<T> (extends org.hamcrest.SelfDescribing) β
β Core contract: boolean matches(Object actual) & void describeMismatch(Object, Description) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββ
βΌ βΌ βΌ
ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ
β STRING MATCHERS β β NUMERIC & COMPARISON MATCHERSβ β COLLECTION & MAP MATCHERS β
ββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββ€
β β’ equalTo / equalToIgnoring..β β β’ greaterThan / lessThan β β β’ hasItem / hasItems β
β β’ containsString / startsWithβ β β’ greaterThanOrEqualTo β β β’ containsInAnyOrder / conta.β
β β’ endsWith / matchesPattern β β β’ closeTo (Double +/- Error) β β β’ hasSize / emptyIterable β
β β’ blankOrNullString / empty..β β β’ notANumber / notNullValue β β β’ hasKey / hasValue / hasEnt.β
ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ
β
βΌ (Combines via Logical Composition)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β COMPOSITE LOGICAL COMBINATORS: allOf(), anyOf(), not(), both().and(), either().or() β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ Injected into REST Assured ValidatableResponse
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GPATH EVALUATOR (GPath Expression βββΊ Extracts Target Object βββΊ Matcher.matches(Target)) β
β .then().body("data.students.credits", everyItem(greaterThanOrEqualTo(4))) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
package com.nikita.restassured.hamcrest;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class StringMatchersTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Demonstrate complete Hamcrest string matching capabilities")
public void testStringAssertions() {
given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
// 1. Exact equality (equivalent to Object.equals)
.body("data.fullName", equalTo("Nikita Sharma"))
// 2. Case-insensitive equality
.body("data.academicTrack", equalToIgnoringCase("enterprise_automation"))
// 3. Substring, prefix, and suffix matches
.body("data.email", containsString("@nikita-infotech.com"))
.body("data.id", startsWith("STU-"))
.body("data.email", endsWith(".com"))
// 4. Case-insensitive and trimmed whitespace matching
.body("data.fullName", equalToCompressingWhiteSpace("Nikita Sharma"))
// 5. Regular expression matching via matchesPattern()
.body("data.id", matchesPattern("^STU-[0-9]{5,}$"))
.body("data.uuid", matchesPattern("^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"))
// 6. Non-empty string and blank validation
.body("data.fullName", not(emptyOrNullString()))
.body("data.secondaryPhone", blankOrNullString());
System.out.println("[β] String matchers validated: exact, regex, casing, prefix, and nullability.");
}
}
greaterThan, lessThanOrEqualTo) and delta-tolerant assertions using closeTo().
package com.nikita.restassured.hamcrest;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class NumberMatchersTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Demonstrate numeric boundary, relational, and floating-point matchers")
public void testNumericAssertions() {
given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219/academic-summary")
.then()
.statusCode(200)
// 1. Strict equality for primitive numbers
.body("summary.completedCredits", is(16))
.body("summary.backlogCount", equalTo(0))
// 2. Relational comparisons (greaterThan, lessThan, etc.)
.body("summary.completedCredits", greaterThan(10))
.body("summary.completedCredits", greaterThanOrEqualTo(16))
.body("summary.backlogCount", lessThanOrEqualTo(1))
// 3. Combined range check (credits must be between 12 and 24 inclusive)
.body("summary.completedCredits", allOf(greaterThanOrEqualTo(12), lessThanOrEqualTo(24)))
// 4. Floating-point tolerance assertion via closeTo(expected, errorDelta)
// Useful for GPA calculations or currency conversions with rounding variations
.body("summary.gpa", closeTo(3.85, 0.05))
// 5. Special numeric states
.body("summary.completionPercentage", not(nanValue()));
System.out.println("[β] Numeric matchers validated: relational ranges, integer equality, and GPA closeTo().");
}
}
hasItem(), contains multiple elements via hasItems(), and ensuring all array elements satisfy a condition using everyItem().
package com.nikita.restassured.hamcrest;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CollectionMembershipTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Verify JSON array elements using hasItem, hasItems, and everyItem")
public void testCollectionMembershipAssertions() {
given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
// 1. Single element presence check inside array
.body("data.fullName", hasItem("Nikita Sharma"))
// 2. Multiple element presence check (Order does not matter; extra items allowed)
.body("data.fullName", hasItems("Nikita Sharma", "Aarav Deshmukh"))
// 3. Negated membership: Assert specific legacy record is NOT present
.body("data.fullName", not(hasItem("Deprecated User")))
// 4. everyItem(): Asserts every element in the collection satisfies the matcher
.body("data.id", everyItem(startsWith("STU-")))
.body("data.enrolledCredits", everyItem(greaterThan(0)))
.body("data.academicTrack", everyItem(notNullValue()))
// 5. Combining everyItem with composite logic
.body("data.enrolledCredits", everyItem(allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(30))));
System.out.println("[β] Collection membership verified: hasItems confirmed candidates; everyItem validated IDs and credits.");
}
}
contains() and containsInAnyOrder(). Demonstrates strict sequence verification, exhaustive unordered matching, and collection size assertions via hasSize().
package com.nikita.restassured.hamcrest;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CollectionOrderingTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Demonstrate strict ordering, unordered exhaustive matching, and size checks")
public void testCollectionOrderingAndSizing() {
given()
.baseUri(BASE_URI)
.queryParam("sort", "id:asc")
.when()
.get("/students/STU-88219/courses")
.then()
.statusCode(200)
// 1. hasSize(): Assert exact number of elements in array
.body("courses", hasSize(3))
.body("courses", not(empty()))
// 2. containsInAnyOrder(): Exhaustive match where order DOES NOT matter.
// MUST contain all listed items and NO extra items!
.body("courses.code", containsInAnyOrder("REST-JAVA-201", "API-PRO-101", "DOCKER-QA-301"))
// 3. contains(): Exhaustive match where ORDER IS STRICTLY ENFORCED.
// Fails if elements appear in a different sequence!
.body("courses.code", contains("API-PRO-101", "DOCKER-QA-301", "REST-JAVA-201"))
// 4. Assert size boundaries using numeric matchers
.body("courses.size()", greaterThanOrEqualTo(1));
System.out.println("[β] Ordering and sizing verified: hasSize(3), containsInAnyOrder(), and strict contains().");
}
@Test(description = "Verify empty array response on clean state")
public void testEmptyCollectionAssertion() {
given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219/disciplinary-actions")
.then()
.statusCode(200)
// Assert array is completely empty
.body("actions", empty())
.body("actions", hasSize(0));
System.out.println("[β] Empty collection asserted successfully.");
}
}
hasKey(), checking value presence via hasValue(), and asserting exact key-value pairs with hasEntry().
package com.nikita.restassured.hamcrest;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class MapMatchersTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Verify JSON dictionary and map structures using hasKey, hasValue, and hasEntry")
public void testMapAndObjectAssertions() {
given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
// 1. hasKey(): Asserts the JSON object contains a specific attribute name
.body("data", hasKey("id"))
.body("data", hasKey("fullName"))
.body("data", hasKey("contactInfo"))
.body("data", not(hasKey("internalPasswordHash")))
// 2. hasValue(): Asserts a map contains a specific value under any key
.body("data.contactInfo", hasValue("Pune"))
// 3. hasEntry(): Asserts an exact key-value pair exists within the object
.body("data.contactInfo", hasEntry("city", "Pune"))
.body("data.contactInfo", hasEntry("postalCode", "411015"))
// 4. hasEntry() combined with matcher expressions
.body("data.contactInfo", hasEntry(equalTo("phone"), startsWith("+91-")));
System.out.println("[β] Map matchers validated: hasKey, hasValue, and hasEntry on nested contactInfo.");
}
}
allOf() (logical AND), anyOf() (logical OR), not() (negation), and fluent syntax (both().and(), either().or()).
package com.nikita.restassured.hamcrest;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CompositeLogicalMatchersTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Demonstrate composite logical operators: allOf, anyOf, not, both, and either")
public void testLogicalCombinators() {
given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
// 1. allOf(): Logical AND - ALL sub-matchers must pass
.body("data.enrolledCredits", allOf(
greaterThanOrEqualTo(1),
lessThanOrEqualTo(30),
not(equalTo(0))
))
// 2. anyOf(): Logical OR - At least ONE sub-matcher must pass
.body("data.academicTrack", anyOf(
equalTo("ENTERPRISE_AUTOMATION"),
equalTo("FULLSTACK_SDET"),
equalTo("CLOUD_DEVOPS_QA")
))
// 3. not(): Logical negation
.body("data.status", not(equalTo("SUSPENDED")))
.body("data.fullName", not(emptyOrNullString()))
// 4. both().and(): Fluent alternative to allOf() with two conditions
.body("data.enrolledCredits", both(greaterThan(0)).and(lessThan(40)))
// 5. either().or(): Fluent alternative to anyOf() with two conditions
.body("data.academicStatus", either(equalTo("ACTIVE")).or(equalTo("PROBATION")));
System.out.println("[β] Composite logical combinators validated: allOf, anyOf, not, both().and(), and either().or().");
}
}
org.hamcrest.MatcherAssert.assertThat() to evaluate assertions independently of REST Assured's fluent .then() pipeline.
package com.nikita.restassured.hamcrest;
import io.restassured.path.json.JsonPath;
import org.hamcrest.MatcherAssert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class StandaloneMatcherAssertTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Demonstrate standalone MatcherAssert.assertThat() on extracted variables")
public void testStandaloneMatcherAssert() {
// Step 1: Execute request and extract JsonPath instance
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
.extract()
.jsonPath();
// Step 2: Extract specific fields into local Java variables
int totalRecords = jsonPath.getInt("pagination.totalRecords");
List<String> studentNames = jsonPath.getList("data.fullName");
String firstStudentId = jsonPath.getString("data[0].id");
// Step 3: Evaluate assertions using MatcherAssert.assertThat()
// Signature: assertThat(String reason, T actual, Matcher super T> matcher)
MatcherAssert.assertThat("Total records must be positive", totalRecords, greaterThan(0));
MatcherAssert.assertThat("Candidate list must contain lead student",
studentNames, hasItem("Nikita Sharma"));
MatcherAssert.assertThat("Student names list size must match pagination",
studentNames, hasSize(totalRecords));
MatcherAssert.assertThat("First student ID must follow canonical format",
firstStudentId, matchesPattern("^STU-[0-9]{5,}$"));
System.out.println("[β] Standalone MatcherAssert.assertThat() validated all extracted variables with descriptive reasons.");
}
}
package com.nikita.restassured.hamcrest;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class HamcrestFailureTriageTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Demonstrate diagnostic failure trace generated by containsInAnyOrder mismatch")
public void testDiagnoseCollectionMismatch() {
// Intentionally assertion against non-existent course to demonstrate failure diagnostics
given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219/courses")
.then()
.statusCode(200)
// Passes if array matches actual: ["API-PRO-101", "REST-JAVA-201", "DOCKER-QA-301"]
.body("courses.code", containsInAnyOrder(
"API-PRO-101",
"REST-JAVA-201",
"DOCKER-QA-301"
));
System.out.println("[β] Collection matched expected course inventory.");
}
// ==========================================================================
// ANATOMY OF A HAMCREST FAILURE TRACE (IF A COURSE WAS MISSING):
// ==========================================================================
// java.lang.AssertionError: 1 expectation failed.
// JSON path courses.code doesn't match.
// Expected: iterable with items ["API-PRO-101", "REST-JAVA-201", "NON-EXISTENT-404"] in any order
// Actual: <[API-PRO-101, REST-JAVA-201, DOCKER-QA-301]>
//
// DIAGNOSTIC BREAKDOWN:
// 1. Expected specifies the full target collection
// 2. Actual prints the raw array returned over the wire
// 3. Immediately reveals: "NON-EXISTENT-404" was expected but "DOCKER-QA-301" was received!
}
HAMCREST MATCHER CATALOG SPECIFICATION MATRIX:
ββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β CATEGORY β MATCHER METHOD SIGNATURE β ARGUMENT TYPES β PRIMARY OPERATIONAL PURPOSE β
ββββββββββββββββββββΌββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ€
β Core Equality β equalTo(T operand) β Object, Primitiveβ Exact value equality (equals) β
β Object Identity β is(T valueOrMatcher) β Object / Matcher β Syntactic decorator or equality β
β String Substring β containsString(String sub) β String β Asserts string contains substring β
β String Boundary β startsWith() / endsWith() β String β Prefix and suffix validation β
β String Regex β matchesPattern(String regex)β String / Pattern β Regular expression verification β
β String Casing β equalToIgnoringCase(String) β String β Case-insensitive comparison β
β String Whitespaceβ equalToCompressingWhiteSpaceβ String β Trims & collapses spaces β
β String Null/Blankβ emptyOrNullString() β N/A (Method) β Checks for null or "" string β
β Relational Num β greaterThan / lessThan β Comparable<T> β Numeric boundary checks (>, <) β
β Relational Num β greaterThanOrEqualTo / <= β Comparable<T> β Inclusive boundary checks (>=, <=) β
β Floating-Point β closeTo(Double val, Delta) β Double, Double β Floating-point tolerance check β
β Collection Item β hasItem(T elementOrMatcher) β Element / Matcherβ Asserts array contains at least 1 β
β Collection Items β hasItems(T... elements) β Varargs Elements β Asserts array contains subset β
β Exhaustive Any β containsInAnyOrder(T... itm)β Varargs Elements β All items present, unordered β
β Exhaustive Order β contains(T... items) β Varargs Elements β All items present, STRICT order β
β Collection Size β hasSize(int expectedSize) β Integer β Exact element count check β
β Collection Empty β empty() / emptyIterable() β N/A (Method) β Asserts array is [] (size == 0) β
β All Items Rule β everyItem(Matcher matcher) β Matcher<?> β Every array element must match β
β Map Key Check β hasKey(String key) β String / Matcher β Asserts JSON object contains key β
β Map Value Check β hasValue(Object value) β Object / Matcher β Asserts JSON object contains val β
β Map Entry Check β hasEntry(Key, Value) β K, V or Matchers β Asserts exact key-value mapping β
β Composite AND β allOf(Matcher... matchers) β Varargs Matchers β All conditions must pass (AND) β
β Composite OR β anyOf(Matcher... matchers) β Varargs Matchers β At least one must pass (OR) β
β Negation β not(Matcher matcher) β Matcher<?> β Inverts matcher evaluation (NOT) β
ββββββββββββββββββββ΄ββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 HAMCREST BEST PRACTICES: β
β 1. Use containsInAnyOrder() for database-backed arrays: Prevents flaky tests from database sort order. β
β 2. Apply everyItem() for uniform collection rules: Validate that all IDs match regex in one assertion. β
β 3. Use closeTo() for calculated floats: Avoid false failures from binary IEEE-754 rounding differences. β
β 4. Combine conditions with allOf() and anyOf(): Express composite business rules declaratively. β
β 5. Provide reason strings in MatcherAssert.assertThat: Add context to failure traces outside BDD chains. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ