Consider the following test scenario:
- Open a browser and login to the application through the login page.
- Close the login page and the browser.
- Re-open the login page to see if you are automatically logged in.
Usually, browser stores the cookies on the first login. However, in WebDriver all session data and cookies are deleted as the window is closed. So, the testing becomes little complex in such scenarios.
But, WebDriver allows you to restore the cookies in the new window, as it can read the information from the browser before closing it, as shown below.
package com.testing.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;
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());
// Read the cookies before closing the browser
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 displayed
Assert.assertTrue(
driver.findElement(By.id(“welcome”)).isDisplayed());
driver.close();
}
}
You might also like: How to Add, Retrieve, and Delete Cookies in WebDriver?