π Method Chaining in Rest Assured π
If you're diving into API automation with Rest Assured, you're probably familiar with the powerful method chaining feature it offers.
π The Core Trio: given()
, when()
, and then()
What Is Method Chaining?
Method chaining in Rest Assured enables seamless specification of:
- Request parameters, headers, body, and authentication (
given()
). - The HTTP method and endpoint to interact with (
when()
). - Response validation using assertions (
then()
).
This flow mirrors the Given-When-Then structure from Behavior-Driven Development (BDD), making your tests easy to understand and maintain.
Example: Testing an API with Method Chaining
Hereβs how you can test a simple GET
API using Rest Assured:
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class ApiTest {
public static void main(String[] args) {
given()
.baseUri("https://api.example.com") // Define base URI
.queryParam("id", 1) // Set query parameter
.header("Authorization", "Bearer token_value") // Set headers
.when()
.get("/users") // Specify HTTP method and endpoint
.then()
.statusCode(200) // Assert status code
.body("name", equalTo("John Doe")) // Validate response body
.log().all(); // Log complete response
}
}
}
Why Use Method Chaining?
β¨ Readable Tests: The BDD structure (given-when-then) is intuitive and self-explanatory. β¨ Reduced Boilerplate: Combines request building, execution, and validation in one seamless chain. β¨ Flexible Validation: Integrates powerful assertion frameworks for response validation.
Β