Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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="";
   		// navigate to your url
        // define your cookie as cookie type object
		Cookie name = new Cookie("CookieDescription", "cookie value");
		// add your cookie
		// now your cookie is being added but your tests needs to get the updated version so 
		// we need to reload the page 

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

	Set 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 to understand all the ways you can benefit from cookies handling.

Happy Testing!

The post How to addcookie with Selenium Webdriver appeared first on Testingrepository - Talking about selenium , and our passion.

This post first appeared on Testing Repository - Creating Testing, please read the originial post: here

Share the post

How to addcookie with Selenium Webdriver


Subscribe to Testing Repository - Creating Testing

Get updates delivered right to your inbox!

Thank you for your subscription