Handling session cookies

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

addCookie(Cookie cookie)

This method adds a cookie.

getCookieNamed(String name)

This method returns the cookie with a specified name.

getCookies()

This method returns all the cookies for current domain.

deleteCookieNamed(String name)

This method deletes the cookie with a specified name.

deleteCookie(Cookie cookie)

This method deletes a cookie.

deleteAllCookies()

This method deletes all the cookies for current domain.

In this recipe, we will see how to read a cookie and check it's value.

Getting ready

Create a new test that will get an instance of WebDriver, navigate to a site, and perform some basic actions and verifications.

How to do it...

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());
}

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.139.8