REST Assured interview question
Explain REST Assured's given/when/then structure and write a basic test
Short answer
given() builds the request (base URI, headers, auth, params, body), when() sends it with an HTTP method, and then() validates the response with status, header and Hamcrest body matchers using GPath. Use extract() to pull values out for later steps.
Answer
REST Assured is a Java DSL for testing HTTP APIs. Its fluent, BDD-style syntax reads like a specification and integrates with JUnit 5 or TestNG.
The three parts
given(): everything about the request: base URI, path and query parameters, headers, content type, authentication, cookies, body, logging.when(): the action, an HTTP method call such asget,post,put,patchordeletewith the path.then(): assertions on the response: status code, headers, content type, response time, and body via Hamcrest matchers.
when() and given() are syntactic sugar; the method call is what sends the request.
A basic test
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class UserApiTest {
@BeforeAll
static void setup() {
baseURI = "https://api.example.test";
basePath = "/v1";
}
@Test
void getsUserById() {
given()
.accept(ContentType.JSON)
.pathParam("id", 42)
.when()
.get("/users/{id}")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("id", equalTo(42))
.body("email", endsWith("@example.com"))
.body("roles", hasItem("viewer"))
.time(lessThan(2000L));
}
@Test
void createsUserAndReturnsId() {
String body = """
{"name": "Ada", "email": "ada@example.com"}
""";
int id = given()
.contentType(ContentType.JSON)
.body(body)
.when()
.post("/users")
.then()
.statusCode(201)
.header("Location", containsString("/users/"))
.body("name", equalTo("Ada"))
.extract().path("id");
given().pathParam("id", id)
.when().get("/users/{id}")
.then().statusCode(200).body("email", equalTo("ada@example.com"));
}
}
GPath for the body
REST Assured uses Groovy’s GPath to navigate JSON:
"address.city"for nested fields."items.size()"for list length."items.name"returns all names as a list, sohasItems("a", "b")works."items.find { it.sku == 'ABC' }.price"filters a list."items.findAll { it.price > 10 }.size()"counts matches.
Numbers with decimals are returned as Float by default, so compare with equalTo(9.99f), or configure JsonConfig with NumberReturnType.BIG_DECIMAL for money.
Extracting values
extract().path("id") returns a single value; extract().response() gives the full Response for headers, cookies and jsonPath(); extract().as(User.class) deserializes into a POJO. This is how you chain requests.
Logging
given().log().ifValidationFails() and then().log().ifValidationFails() print the request and response only when something fails, which keeps CI logs clean but debuggable.
What interviewers look for
- Clear explanation of what belongs in given, when and then.
- Correct static imports and Hamcrest matchers.
- GPath navigation of nested JSON and lists.
- Using extract() to chain calls and verify persistence.
A strong answer covers
- given() sets up the request: headers, params, auth, body
- when() performs the HTTP call
- then() validates status, headers and body with Hamcrest matchers
- GPath expressions to navigate JSON
- extract() to reuse response values