Cookie management in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; public class CookieManagementTest { public static void main(String[] args) { // Set up ChromeDriver (assumes chromedriver is in system PATH) WebDriver driver = new ChromeDriver(); try { // Navigate to example.com driver.get("https://example.com"); // Wait until page title contains 'Example Domain' to ensure page loaded new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.titleContains("Example Domain")); // Create a cookie named 'testCookie' with value 'cookieValue123' Cookie testCookie = new Cookie.Builder("testCookie", "cookieValue123") .domain("example.com") .path("/") .build(); // Add cookie to browser driver.manage().addCookie(testCookie); // Retrieve cookie by name Cookie retrievedCookie = driver.manage().getCookieNamed("testCookie"); // Assert cookie value is 'cookieValue123' if (retrievedCookie == null) { throw new AssertionError("Cookie 'testCookie' was not found after adding."); } if (!"cookieValue123".equals(retrievedCookie.getValue())) { throw new AssertionError("Cookie value mismatch. Expected 'cookieValue123' but got '" + retrievedCookie.getValue() + "'."); } // Delete the cookie named 'testCookie' driver.manage().deleteCookieNamed("testCookie"); // Verify cookie no longer exists Cookie deletedCookie = driver.manage().getCookieNamed("testCookie"); if (deletedCookie != null) { throw new AssertionError("Cookie 'testCookie' still exists after deletion."); } System.out.println("Test passed: Cookie management works as expected."); } finally { // Close browser driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate cookie management on https://example.com.
First, it opens the browser and navigates to the site. It waits until the page title contains 'Example Domain' to ensure the page is fully loaded.
Then, it creates a cookie named 'testCookie' with the value 'cookieValue123' and adds it to the browser.
Next, it retrieves the cookie by name and asserts that the value matches the expected value.
After that, it deletes the cookie and verifies that it no longer exists.
Finally, it prints a success message and closes the browser to clean up.
This approach uses explicit waits, meaningful variable names, and proper assertions to ensure reliability and clarity.
Now add data-driven testing to add and verify cookies with 3 different name-value pairs.
Practice
Solution
Step 1: Understand what cookies do
Cookies store small data such as user sessions or preferences to remember users.Step 2: Relate to Selenium's cookie management
Selenium allows adding, retrieving, and deleting cookies to simulate user sessions during tests.Final Answer:
To store and manipulate small pieces of data like user sessions -> Option BQuick Check:
Cookies = user session data [OK]
- Confusing cookies with browser window controls
- Thinking cookies locate page elements
- Assuming cookies run JavaScript
Solution
Step 1: Recall Selenium cookie API
Cookies are added via driver.manage().addCookie() method with a Cookie object.Step 2: Check syntax correctness
driver.manage().addCookie(new Cookie("name", "value")); uses correct method and creates a new Cookie object properly.Final Answer:
driver.manage().addCookie(new Cookie("name", "value")); -> Option DQuick Check:
Use driver.manage().addCookie(new Cookie()) [OK]
- Calling addCookie directly on driver
- Using incorrect method names like cookieAdd
- Passing strings instead of Cookie objects
Cookie cookie = new Cookie("session", "abc123");
driver.manage().addCookie(cookie);
Cookie retrieved = driver.manage().getCookieNamed("session");
System.out.println(retrieved.getValue());Solution
Step 1: Add cookie named "session" with value "abc123"
The code adds a cookie with name "session" and value "abc123" to the browser.Step 2: Retrieve cookie by name and print its value
driver.manage().getCookieNamed("session") returns the cookie object, and getValue() prints "abc123".Final Answer:
abc123 -> Option AQuick Check:
getCookieNamed("session").getValue() = abc123 [OK]
- Expecting cookie name instead of value
- Assuming null if cookie not found (but it is added)
- Thinking exception is thrown when cookie exists
driver.manage().deleteCookie("session");Solution
Step 1: Check deleteCookie method signature
deleteCookie expects a Cookie object, not a String name.Step 2: Correct usage
To delete by name, use deleteCookieNamed(String name) instead.Final Answer:
deleteCookie method requires a Cookie object, not a String -> Option CQuick Check:
deleteCookie(Cookie) vs deleteCookieNamed(String) [OK]
- Passing String to deleteCookie instead of Cookie object
- Confusing deleteCookie and deleteCookieNamed methods
- Calling deleteCookie on wrong object
Solution
Step 1: Delete cookie by name "user"
Use deleteCookieNamed("user") to remove the cookie by its name.Step 2: Verify cookie no longer exists
getCookieNamed("user") returns null if cookie is deleted; assert null confirms deletion.Final Answer:
driver.manage().deleteCookieNamed("user"); assert driver.manage().getCookieNamed("user") == null; -> Option AQuick Check:
Deleted cookie returns null [OK]
- Checking getValue() on null cookie causing NullPointerException
- Using deleteCookie with Cookie object without correct value
- Asserting cookie still exists after deletion
Ready to prove it?
Pass the test and this pattern moves unknown
