Understanding Restassured BDD Method- Given, When,Then
Given
Sets up the preconditions for the request — base URI, headers, query parameters, or request body.
When
Specifies the actual action to perform — the HTTP method and endpoint, such as .get("/users") or .post("/login").
Then
Defines the expected outcome — assertions on status code, headers, or response body content.
given().header("Content-Type", "application/json")
.when().post("/login")
.then().statusCode(200).body("token", notNullValue());
What Belongs in Each Block
Thinking of the three blocks as separate responsibilities keeps tests readable. A useful rule: given() describes the request, when() fires it, and then() judges the response.
| Block | Common methods |
|---|---|
given() | baseUri, basePath, header, contentType, queryParam, pathParam, auth(), body, spec |
when() | get, post, put, patch, delete |
then() | statusCode, contentType, header, body, time, extract() |
A Full POST Test, Line by Line
The short snippet on this page hides the imports that make the fluent style work. Rest Assured methods and Hamcrest matchers are usually imported statically:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
public class CreateUserTest {
@Test
public void createUserReturns201() {
String payload = "{ \"name\": \"Neha\", \"job\": \"tester\" }";
String id =
given()
.baseUri("https://api.example.com")
.contentType(ContentType.JSON)
.body(payload)
.log().ifValidationFails()
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo("Neha"))
.body("id", notNullValue())
.time(lessThan(3000L))
.extract().path("id");
System.out.println("Created user " + id);
}
}
Reading it top to bottom: the request is set up with a base URI, JSON content type and a body. Logging is enabled only when an assertion fails, which keeps passing runs quiet. The post call sends the request. The then() block checks the status, two fields of the JSON response and the response time. Finally extract().path("id") pulls the new id out for use in a follow-up request, such as a GET or DELETE.
Reusing Setup With Specifications
Repeating the base URI and headers in every test is tedious. A RequestSpecification stores the common part, and a ResponseSpecification stores shared checks:
RequestSpecification req = new RequestSpecBuilder()
.setBaseUri("https://api.example.com")
.setContentType(ContentType.JSON)
.build();
ResponseSpecification ok = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.build();
given().spec(req).pathParam("id", 7)
.when().get("/users/{id}")
.then().spec(ok).body("id", equalTo(7));
Checking nested JSON with GPath
The string passed to body() is a GPath expression, which lets you reach into arrays and nested objects without writing a parser. Suppose a list endpoint returns users inside a data array:
given().spec(req).queryParam("page", 2)
.when().get("/users")
.then()
.statusCode(200)
.body("data.size()", greaterThan(0))
.body("data[0].email", containsString("@"))
.body("data.first_name", hasItems("Rahul", "Meera"))
.body("data.find { it.id == 9 }.last_name", equalTo("Verma"));
The first check confirms the array is not empty, the second inspects one element, the third collects a field from every element and checks that certain values are present, and the last searches the array for a matching record. Several body() calls can be chained, and each failure message names the exact path that did not match, which makes debugging much faster.
Errors Beginners Run Into
- Missing static imports. Without them,
given()andequalTo()will not compile. - No content type on POST. Many APIs reject a JSON body sent without
application/json. - Asserting in the wrong block. Checks placed before
when()do nothing useful; validation lives inthen(). - Hard-coded test data. Using the same email every run can cause "already exists" failures. Generate unique values.
- Logging everything always.
log().all()on every request floods the console and may print tokens. PreferifValidationFails().
Ready to master real-world software testing?
Learn manual and automation testing hands-on with mentor-led sessions.