Given/When/Then
Explore the use of given, when, and then methods in REST Assured to build request specifications, send HTTP requests, and validate responses. This lesson helps you construct API test scripts with proper headers, parameters, and body content for automation.
given()
It is used in building the DSL expression request with any additional information like headers, params, message body, authentication, etc., before making any HTTP Request like POST, GET, PUT, DELETE using given() method.
Example 1:
RestAssured.given()
.header("header1","value1")
.header("header2", "value2")
.param("param1","paramValue")
.body(body)
.post(url);
In the example above, before sending the POST request, headers(…), params(…) and body(…) are added to the request builder.
Example 2:
RestAssured.given()
.get(url);
In this example, no extra information is added to the request builder before making a GET request.
when()
Using when(), you can start building the DSL expression by sending a request without any parameters, headers or body etc.
when() can be used with given() or independently in the DSL expression.
Example 1:
RestAssured.given()
.param("firstName", "John")
.param("lastName", "Doe")
.when()
.get("/greet");
In the example above, when() is used with given() in the DSL expression to pass some parameters with the request.
Example 2:
RestAssured.when()
.get(url);
In the DSL expression above, there is no additional information like headers or params passed while making a get(URL) call.
then()
It is always used with either given(), when(), or with both methods in the DSL expression. It returns a validatable response.
Example:
RestAssured.given().
.param("firstName", "John")
.param("lastName", "Doe")
.when()
.get("/greet")
.then()
.body("greeting", equalTo("John Doe"));
In the next few lessons, we’ll use the learning of given/when/then to automate an HTTP request/response.
In the next lesson, we will learn how to automate an HTTP GET request using REST Assured.