Q6 of 40 · REST Assured

How do you assert the status code and a JSON field in a single chain?

REST AssuredJuniorrest-assuredassertionsjsonpathhamcrestfundamentals

Short answer

Short answer: .statusCode() and .body() both live inside then() and chain on ValidatableResponse — add as many as needed. The first argument to .body() is a JsonPath expression; the second is a Hamcrest matcher. All assertions run before the test reports failure, so one execution shows every mismatch.

Detail

Everything after .then() returns ValidatableResponse, so assertions compose freely:

.then()
    .statusCode(200)
    .contentType(ContentType.JSON)
    .body("id",          equalTo(1))
    .body("status",      equalTo("SHIPPED"))
    .body("items.size()", greaterThan(0))
    .body("items[0].sku", notNullValue())

JsonPath syntax in body()'s first argument:

  • "address.city" — nested field via dot notation
  • "items[0].price" — first array element's field
  • "items.size()" — array length (Groovy GPath)
  • "items.find{it.active}.name" — Groovy predicate (advanced)

Common Hamcrest matchers: equalTo, not, nullValue, notNullValue, containsString, hasItem, hasSize, greaterThan, lessThan, everyItem.

// EXAMPLE

@Test
void getOrder_returnsCompleteDetails() {
    given()
        .baseUri("https://api.example.com")
        .header("Authorization", "Bearer " + token)
    .when()
        .get("/orders/99")
    .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .body("id",            equalTo(99))
        .body("status",        equalTo("SHIPPED"))
        .body("items.size()",  greaterThan(0))
        .body("items[0].sku",  notNullValue())
        .body("total",         greaterThan(0.0f))
        .body("shippedAt",     not(emptyOrNullString()));
}

// WHAT INTERVIEWERS LOOK FOR

Chaining multiple assertions on ValidatableResponse, JsonPath dot-notation for nested fields and array indexing, and correct Hamcrest matcher usage. Knowing that all assertions run before reporting is a strong signal.

// COMMON PITFALL

Using .extract().as(Map.class) and then manual assertEquals — this throws away REST Assured's readable failure messages and makes the test significantly more verbose.