</>

Technology

Rest Assured

Difficulty

Beginner

Interview Question

What is BDD (Given/When/Then) syntax in Rest Assured and how does it work?

Answer

BDD Syntax in Rest Assured — Given / When / Then

Rest Assured is designed around BDD (Behavior-Driven Development) syntax, making API tests highly readable and self-documenting.

The Three Pillars

Java
given()      // GIVEN: Set up the request (preconditions)
    .when()  // WHEN:  Perform the action (send request)
    .then()  // THEN:  Validate the result (assertions)

Complete BDD Example

Java
@Test
public void testGetUserById() {

    given()
        // GIVEN: I have a valid auth token and request spec
        .header("Authorization", "Bearer " + token)
        .header("Accept", "application/json")

    .when()
        // WHEN: I GET user with id 2
        .get("https://reqres.in/api/users/2")

    .then()
        // THEN: I should get a 200 with correct data
        .statusCode(200)
        .contentType("application/json")
        .body("data.id",         equalTo(2))
        .body("data.first_name", equalTo("Janet"))
        .body("data.email",      containsString("@reqres.in"))
        .time(lessThan(2000L));
}

Mapping BDD to English

CODE
GIVEN I have a logged-in user with admin role
WHEN  I send DELETE to /api/users/5
THEN  the response status should be 204
AND   the user should no longer exist
Java
given()
    .header("Authorization", "Bearer " + adminToken)   // logged-in admin
.when()
    .delete("/api/users/5")                              // send DELETE
.then()
    .statusCode(204);                                    // 204 No Content

// AND verify user is gone
given().when().get("/api/users/5").then().statusCode(404);

BDD vs Non-BDD Style

Java
// BDD Style (Fluent) — more readable
given()
    .contentType(ContentType.JSON)
    .body("{ \"name\": \"John\" }")
    .when()
    .post("/api/users")
    .then()
    .statusCode(201)
    .body("name", equalTo("John"));

// Non-BDD Style — also valid
Response response = given()
                        .contentType(ContentType.JSON)
                        .body("{ \"name\": \"John\" }")
                        .when()
                        .post("/api/users");

assertEquals(response.getStatusCode(), 201);
assertEquals(response.path("name"), "John");

When to Use Each Style

StyleBest For
BDD (fluent)Single assertions, readable test output
Non-BDDExtracting values for use in next step (chaining)
MixedValidate response AND extract a value
Java
// Mixed — validate AND extract
String userId = given()
                    .body("{ \"name\": \"John\" }")
                    .contentType(ContentType.JSON)
                    .when()
                    .post("/api/users")
                    .then()
                    .statusCode(201)           // validate
                    .extract().path("id");     // extract

Follow AutomateQA

Related Topics