Applying Hamcrest Assertions On Response Validations Using Restassured
What is Hamcrest?
Hamcrest is a library of readable "matchers" (like equalTo, containsString, greaterThan) used to write flexible, expressive assertions.
Examples
.body("data.id", equalTo(2))
.body("data.email", containsString("@reqres.in"))
.body("data.id", greaterThan(0))
.body("support.text", not(isEmptyString()));
Why Testers Use Hamcrest
Hamcrest matchers make assertions read almost like natural language, and support far more nuanced checks than simple equality — such as ranges, patterns, and collection contents.
A Complete Test with Static Imports
Hamcrest matchers become readable only when they are imported statically. Here is a full TestNG test that checks status, headers, single fields, lists and response time in one chain:
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;
public class UserApiTest {
@Test
public void listUsersReturnsValidData() {
given()
.baseUri("https://api.example.com")
.queryParam("page", 1)
.when()
.get("/users")
.then()
.statusCode(200)
.contentType(containsString("application/json"))
.body("page", equalTo(1))
.body("data", hasSize(greaterThan(0)))
.body("data.id", everyItem(greaterThan(0)))
.body("data.email", hasItem(endsWith("@example.com")))
.body("data[0]", hasKey("first_name"))
.time(lessThan(3000L));
}
}
Paths like data.id use GPath. When data is a list, data.id returns a list of every id, which is why collection matchers such as everyItem and hasItem fit naturally.
Matchers Grouped by Purpose
| Purpose | Matchers | Example |
|---|---|---|
| Equality | equalTo, not | body("status", equalTo("active")) |
| Numbers | greaterThan, lessThanOrEqualTo, closeTo | body("rating", lessThanOrEqualTo(5)) |
| Strings | containsString, startsWith, matchesPattern, equalToIgnoringCase | body("code", matchesPattern("[A-Z]{3}\\d+")) |
| Collections | hasItem, hasItems, hasSize, everyItem, contains | body("tags", hasItems("java", "api")) |
| Maps and nulls | hasKey, nullValue, notNullValue | body("token", notNullValue()) |
| Combining | allOf, anyOf | body("age", allOf(greaterThan(17), lessThan(66))) |
You can also filter with GPath before matching. For instance, body("data.find { it.id == 2 }.email", equalTo("janet@example.com")) picks one record by id and checks its email.
Type Traps and Other Common Failures
- Decimal numbers: by default Rest Assured reads JSON decimals as
Float, soequalTo(19.99), which is a double, fails. UseequalTo(19.99f)or configure the JSON path number type. - Large integers: long values may be returned as
Long, so compare withequalTo(9876543210L). - contains vs hasItems:
containsrequires the exact list in exact order;hasItemsonly checks that the items exist somewhere. - Wrong import: mixing
org.hamcrest.Matcherswith similarly named methods from other libraries causes confusing compile errors.
Checklist for Strong Response Validation
- Status code and content type checked first.
- Key business fields validated with precise matchers.
- List sizes and item rules verified, not just the first element.
- Response time bounded, using a generous limit to avoid flaky tests.
Reusing Expectations Across Tests
When many tests check the same things, such as status 200 and a JSON content type, repeating those lines everywhere adds noise. Rest Assured lets you build a ResponseSpecification once and attach it to any request:
ResponseSpecification okJson = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.build();
given().when().get("/users/2").then().spec(okJson).body("data.id", equalTo(2));
Each test then focuses only on the fields that make it different. If the API later changes its content type or a common header, you update one place instead of fifty test methods. Teams usually keep these shared specifications in a base test class or a small helper so new testers can follow the same pattern from day one.
Ready to master real-world software testing?
Learn manual and automation testing hands-on with mentor-led sessions.