How to addcookie with Selenium Webdriver


641
1 comment, 641 points
how to addcookie with selenium webdriver
how to addcookie with selenium webdriver

How to addcookie with Selenium Webdriver

There are situation when we need to addcokkie with selenium webdriver in order to pre establish a behaviour in our browser for the tests that are going to be executed after that.

For example when you first open your web app you have an overlay over the page , like a sort of user guide , so every time you execute your tests this overlay will not leave you to interact with the interface as all the web-elements are hidden behind it. In this situation you have an option every time you see it you close it like an user does or usually when this is closed developers write a cookie for it to know to to show it again for that session.

If you choose the first option to find it and click on it that’s an extra request to the server and from performance point of view you might not want to do that .

So you can choose option number 2 when you pre set the cookie in your browser.

addcookie with Selenium Webdriver
// init your browser driver = new FirefoxDriver(); // define to your url String URL="http://example.com"; // navigate to your url driver.navigate().to(URL); // define your cookie as cookie type object Cookie name = new Cookie("CookieDescription", "cookie value"); // add your cookie driver.manage().addCookie(name); // now your cookie is being added but your tests needs to get the updated version so // we need to reload the page driver.navigate().refresh();
addcookie

You can simply check if your cookie has been added to your browser with the following code :

 Set<Cookie> allCookies = driver.manage().getCookies(); for(Cookie getAllCookies :allCookies) { System.out.println(getAllCookies ); }
output the cookies

In one of the previous project I was using addcookie to handle a 2 steps authentication¬†. Let me explain you how , Before all tests were supposed to start¬† I was running the actual 2 steps authentication and generate all cookies for that session that was valid for 1 hour, I was outputting the cookies into a shared location where all my tests had access to and each tests was using those cookies and add it to the session so for all further tests I didn’t had to perform the authentication and my test execution time was improved.

You can check more selenium performance tips here .

I advise you have a look at the Cookie.java to understand all the ways you can benefit from cookies handling.

Happy Testing!


Like it? Share with your friends!

641
1 comment, 641 points

What's Your Reaction?

cute cute
0
cute
scary scary
0
scary
wtf wtf
1
wtf
geek geek
0
geek
WIN WIN
0
WIN
Love Love
0
Love
OMG OMG
0
OMG
Angry Angry
0
Angry
Lol Lol
0
Lol
Test engineer

One Comment

Your email address will not be published. Required fields are marked *

Choose A Format
Trivia quiz
Story