Handling cookies and sessions are an important aspect of testing web applications. Rest Assured provides several methods for handling cookies and sessions.
-
Capturing cookies: You can capture cookies from a response using the extract().response() method, and then store them for later use. Here's an example:
-
Reusing cookies: You can reuse cookies in subsequent requests by setting them as a header using the header() method. Here's an example:
Managing sessions: You can manage user sessions by capturing and reusing cookies as described above. For example, you can log in to a website by sending a POST request with the user's credentials, and then capture the session cookie. You can then reuse the session cookie in subsequent requests to simulate a logged-in user session.
Response response = given()
.get("https://example.com/api")
.then()
.extract().response();
String cookieValue = response.getCookie("session_id");
In this example, the getCookie() method is used to extract the value of the session_id cookie from the response.
given()
.header("Cookie", "session_id=" + cookieValue)
.get("https://example.com/api")
.then()
.statusCode(200);
In this example, the header() method is used to set the session_id cookie value as a header in the subsequent request.
Response response = given()
.param("username", "testuser")
.param("password", "testpassword")
.post("https://example.com/login")
.then()
.extract().response();
String sessionCookie = response.getCookie("session_id");
given()
.header("Cookie", "session_id=" + sessionCookie)
.get("https://example.com/profile")
.then()
.statusCode(200);
In this example, the user logs in by sending a POST request to the login endpoint with the username and password parameters. The session cookie is then extracted from the response and set as a header in the subsequent request to the user's profile page.
These are some of the ways in which Rest Assured can be used to handle cookies and sessions.
Comments
Post a Comment