Websites use cookies to store user preferences, login information, and various other details of the client. The Selenium WebDriver API provides various methods to manage these cookies during testing. Using these methods, we can read cookie values, add cookies, and delete cookies during the test. This can be used to test how the application reacts when cookies are manipulated. The WebDriver.Options
interface provides the following methods to manage cookies:
Method |
Description |
---|---|
| |
| |
| |
| |
| |
|
In this recipe, we will see how to read a cookie and check it's value.
Create a new test that will get an instance of WebDriver
, navigate to a site, and perform some basic actions and verifications.
Let's create a test that reads a cookie and checks its value, as shown in the following code example:
@Test public void testCookies() { driver.get("http://demo.magentocommerce.com/"); // Get the Your language dropdown as instance of Select class Select language = new Select(driver.findElement(By.id("select-language"))); // Check default selected option is English assertEquals("English", language.getFirstSelectedOption().getText()); // Store cookies should be none Cookie storeCookie = driver.manage().getCookieNamed("store"); assertEquals(null, storeCookie); // Select an option using select_by_visible text language.selectByVisibleText("French"); // Store cookie should be populated with selected country storeCookie = driver.manage().getCookieNamed("store"); assertEquals("french", storeCookie.getValue()); }
The WebDriver.Options
interface provides various methods to add, read, change, and delete cookies. In this example, when we change the language of the store, a cookie is used to store language preference. We can read this cookie and its value in following way:
Cookie storeCookie = driver.manage().getCookieNamed("store"); assertEquals("french", storeCookie.getValue());
We called the getCookieNamed()
method by passing the name of the cookie. It returns an instance of the Cookie
object. The Cookie
object has various methods of reading value, domain, and so on.
3.16.139.8