← Back to libraryQuestion 229 of 468
🔌REST AssuredBeginner

The given / when / then BDD Syntax

📌 Definition:

REST Assured structures a test in three parts: given() sets up the request (headers, params, body, auth), when() specifies the action (the HTTP method + endpoint), and then() validates the response.

📖 Detailed Explanation:

This Behavior-Driven style makes tests self-documenting. given() is the arrange phase — base URI, headers, query/path params, request body, authentication. when() is the act phase — .get(), .post(), .put(), .delete() with the path. then() is the assert phase — .statusCode(), .body(...), .header(...), .time(...). You chain assertions in then(), and can add .extract() to pull values out for further use. The three keywords are static imports from io.restassured.RestAssured and the Hamcrest matchers, and while the given/when/then split is conventional, all three are technically optional.

🔑 Key Points:
  • given() = arrange (headers, params, body, auth)
  • when() = act (get/post/put/delete + endpoint)
  • then() = assert (statusCode, body, header, time)
  • Chain assertions in then(); .extract() pulls values out
🌍 Real-World Example:

A create-and-verify test: given().header('Authorization', token).contentType(JSON).body(payload).when().post('/orders').then().statusCode(201).body('status', equalTo('CREATED')).

🎯 Scenario-Based Interview Question:

Explain what each part of given().queryParam('id', 5).when().get('/user').then().statusCode(200) does.