Tuesday 15 March 2016

How to Restore Cookies in New Browser Window in selenium webdriver

How to Restore Cookies in New Browser Window in selenium webdriver:
=======================================================
Suppose we have to test for the following scenario:

1. Go to login page and login to the application
2. Close the browser
3. Open the browser and go to login page – the user should not see login form and should be already logged in.

On first login, cookies are stored in the browser. In WebDriver, when the browser window is closed, all session data and cookies are deleted, so the testing of the above scenario becomes impossible.

Luckily, WebDriver has functionality to read the cookies from the browser before closing it and then restore the cookies in the new browser window.

Restore Cookies in New BrowserJava

package com.testingexcellence.webdriver
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
<div style="clear:both; margin-top:0em; margin-bottom:1em;"><a href="http://www.testingexcellence.com/how-to-resize-browser-window-in-webdriver/" target="_blank" rel="nofollow" class="udf9e9f4d3032696469537e117b295605"><div style="padding-left:1em; padding-right:1em;"><span class="ctaText"></span>  <span class="postTitle">How to Resize Browser Window in WebDriver</span></div></a></div>
import java.util.Set;

public class CookieTest {
    WebDriver driver;

    @Test
    public void login_state_should_be_restored() {
        driver = new FirefoxDriver();

        driver.get("http://www.example.com/login");
        driver.findElement(By.id("username")).sendKeys("admin");
        driver.findElement(By.id("password")).sendKeys("12345");
        driver.findElement(By.id("login")).click();

        Assert.assertTrue(
              driver.findElement(By.id("welcome")).isDisplayed());

        //Before closing the browser, read the cookies
        Set<Cookie> allCookies = driver.manage().getCookies();

        driver.close();

        //open a new browser window
        driver = new FirefoxDriver();

        //restore all cookies from previous session
        for(Cookie cookie : allCookies) {
            driver.manage().addCookie(cookie);
        }

        driver.get("http://www.example.com/login");
       
        //Login page should not be disaplyed
        Assert.assertTrue(
              driver.findElement(By.id("welcome")).isDisplayed());
       
        driver.close();
    }
}

No comments:

Post a Comment