Q4 of 40 · REST Assured

Walk through the basic given/when/then syntax of a REST Assured test.

REST AssuredJuniorrest-assuredgiven-when-thenfundamentalsapi-testing

Short answer

Short answer: given() sets up the request (base URI, headers, auth, body); when() fires the HTTP method and path; then() holds assertions. Each method returns the same object so assertions chain. All three sections are optional — a minimal test can call .when().get(path).then().statusCode(200).

Detail

given() — request specification:

  • Base URI, path params, query params
  • Headers, cookies, auth
  • Request body and content type
  • Logging: .log().all() or .log().ifValidationFails()

when() — HTTP verb and endpoint:

  • .get(path), .post(path), .put(path), .patch(path), .delete(path)
  • .request(method, path) for dynamic methods

then() — response assertions (returns ValidatableResponse):

  • .statusCode(200)
  • .body("field", equalTo("value")) — JsonPath assertion with Hamcrest matcher
  • .contentType(ContentType.JSON)
  • .extract() to pull out values for subsequent steps

You can chain as many .body() assertions as needed — all run before the test reports failure, so one test shows all issues at once.

// EXAMPLE

GivenWhenThenTest.java

@Test
void createUser_returns201WithBody() {
    given()
        .baseUri("https://api.example.com")
        .contentType(ContentType.JSON)
        .header("Authorization", "Bearer " + token)
        .body("{ \"name\": \"Alice\", \"email\": \"alice@example.com\" }")
    .when()
        .post("/users")
    .then()
        .statusCode(201)
        .contentType(ContentType.JSON)
        .body("id",    notNullValue())
        .body("name",  equalTo("Alice"))
        .body("email", equalTo("alice@example.com"));
}

// WHAT INTERVIEWERS LOOK FOR

Correct mental model of the three sections and what belongs in each. Knowing that then() accepts chained Hamcrest matchers and that all assertions run before reporting. Bonus: awareness of .log().ifValidationFails() for CI-friendly debugging.

// COMMON PITFALL

Putting the path in given() instead of when(). The endpoint belongs on the HTTP verb call: .when().get("/users/1"), not as a given() configuration.