Given/When/Then & Assertions
Basic Requests
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
@BeforeAll
static void setup() {
RestAssured.baseURI = "https://api.example.com";
}
@Test
void getUser_returnsExpectedFields() {
given()
.header("Authorization", "Bearer " + token)
.queryParam("expand", "profile")
.when()
.get("/users/1")
.then()
.statusCode(200)
.body("name", equalTo("Alice"))
.body("email", containsString("@"))
.header("Content-Type", containsString("application/json"));
}POST with a Body & Extracting Values
@Test
void createUser_thenUseReturnedId() {
String userJson = "{ \"name\": \"Bob\" }";
int newId = given()
.contentType(ContentType.JSON)
.body(userJson)
.when()
.post("/users")
.then()
.statusCode(201)
.extract().path("id"); // extract for use in a LATER request
given()
.when().get("/users/" + newId)
.then().statusCode(200).body("name", equalTo("Bob"));
}
// A POJO works too — REST Assured serializes it automatically
// given().contentType(ContentType.JSON).body(new User("Bob")).post("/users");Debugging
given()
.log().all() // print the full request before sending
.when()
.get("/users/1")
.then()
.log().ifValidationFails() // only print response details on assertion failure
.statusCode(200);Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free