#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Rest Assured

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

PurposeMatchersExample
EqualityequalTo, notbody("status", equalTo("active"))
NumbersgreaterThan, lessThanOrEqualTo, closeTobody("rating", lessThanOrEqualTo(5))
StringscontainsString, startsWith, matchesPattern, equalToIgnoringCasebody("code", matchesPattern("[A-Z]{3}\\d+"))
CollectionshasItem, hasItems, hasSize, everyItem, containsbody("tags", hasItems("java", "api"))
Maps and nullshasKey, nullValue, notNullValuebody("token", notNullValue())
CombiningallOf, anyOfbody("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, so equalTo(19.99), which is a double, fails. Use equalTo(19.99f) or configure the JSON path number type.
  • Large integers: long values may be returned as Long, so compare with equalTo(9876543210L).
  • contains vs hasItems: contains requires the exact list in exact order; hasItems only checks that the items exist somewhere.
  • Wrong import: mixing org.hamcrest.Matchers with 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.

Explore Course