Manipulating cookies in selenium Webdriver sessions is really easy, it can enhance your testing and you can make more detailed logs and pinpointing issues.
To be able to insert a cookie you have to have a Webdriver instance at hand, you have to create a Webdriver cookie add it to your Webdriver instance.
To create a cookie you can use on of the constructors of the org.openqa.selenium.Cookie class:

Cookie(java.lang.String name, java.lang.String value)

Create a cookie for the default path with the given name and value with no expiry set.

Cookie(java.lang.String name, java.lang.String value, java.lang.String path)

Create a cookie with the given name value and path.

Cookie(java.lang.String name, java.lang.String value, java.lang.String path, java.util.Date expiry)

Creates an insecure non-httpOnly cookie with no domain specified.

Cookie(java.lang.String name, java.lang.String value, java.lang.String domain, java.lang.String path, java.util.Date expiry)

Creates an insecure non-httpOnly cookie.

Cookie(java.lang.String name, java.lang.String value, java.lang.String domain, java.lang.String path, java.util.Date expiry, boolean isSecure)

Creates a non-httpOnly cookie.

Cookie(java.lang.String name, java.lang.String value, java.lang.String domain, java.lang.String path, java.util.Date expiry, boolean isSecure, boolean isHttpOnly)

Creates a cookie.


To add the cookie you can use the wedriver’s instance manage().addcookie() function like this:

getMyDriver().manage().addCookie(cookie);

There are cases when you have to edit the session cookies:
To do it, you have to read out the cookie from one of the sessions, create a new cookie with the new data and then delete the old cookie.

Let me explain it on an example:

// preset data
String cookieName = "OWASP_TOKEN";
String testToken= "ASD123";

// get the cookie with the name OWASP_TOKEN
Cookie owaspTokenCookie = htmlUnitDriver.manage().getCookieNamed(cookieName);

//extract the path from the original cookie
String path = owaspTokenCookie.getPath();

// delete the old cookie
getMyDriver().manage().deleteCookie(owaspTokenCookie);	

// create the new cookie with the updated data
Cookie selCookie = new Cookie(cookieName, testToken, path);

// add the cookie to the session
getMyDriver().manage().addCookie(selCookie);

And after this we can continue with your test code.

Using this technique, you can set the same cookies to multiple tests in a parallel test run, or you can speed up the test run by skipping some ui sections.

There is one last thing of which you have to be aware, webdriver only allows cookie manipulation if you already loaded a page.

For additional example you can visit Program Creek
The javadoc for the Cookie class: Selemnium HQ

Posted By Tihomir Turzai

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>