0
0
Selenium Javatesting~15 mins

Cookie management in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify cookie management on example.com
Preconditions (3)
Step 1: Open browser and navigate to https://example.com
Step 2: Add a cookie with name 'testCookie' and value 'cookieValue123'
Step 3: Retrieve the cookie named 'testCookie' and verify its value is 'cookieValue123'
Step 4: Delete the cookie named 'testCookie'
Step 5: Verify that the cookie named 'testCookie' no longer exists
✅ Expected Result: The cookie 'testCookie' is added successfully with correct value, then deleted and no longer present
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Assert cookie value equals 'cookieValue123' after adding
Assert cookie is null after deletion
Best Practices:
Use WebDriver's manage().getCookies() and manage().addCookie() methods
Use explicit waits if needed before cookie operations
Use meaningful variable names and comments
Close browser after test
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Not specifying the domain when creating a cookie
Using Thread.sleep() instead of explicit waits before cookie operations
Not checking if the cookie exists before accessing its value
Not closing the browser after test execution
Bonus Challenge

Now add data-driven testing to add and verify cookies with 3 different name-value pairs.

Show Hint