How to set cookies in Seleniu WebDriver

How to set cookies in selenium WebDriver.

Say you have scenario

  1. Open Application
  2. Fill credentials
  3. User logged into application
  4. Close the browser
  5. Open the browser
  6. Now user should be directly logged in as not cleared session / cookies

To automate this scenario, how to add cookies to the browser.

Below is the code which I wrote how ever, after closing and browser of logged in user and opening new browser again, user still displaying with enter credentials page, expected to display user logged in

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Cookies {

static WebDriver obj;
@Test
public void Gmail() throws InterruptedException {
System.setProperty(“webdriver.gecko.driver”,”D:\\SELENIUM\\geckodriver.exe”);
obj=new FirefoxDriver();
obj.manage().window().maximize();
obj.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
obj.get(“https://mail.google.com”);
obj.findElement(By.id(“Email”)).sendKeys(“UserEmail”);
obj.findElement(By.id(“next”)).click();
Thread.sleep(2000);
obj.findElement(By.id(“Passwd”)).sendKeys(“password$167”);
obj.findElement(By.id(“signIn”)).click();
Thread.sleep(3000);
Set<Cookie> allCookies=obj.manage().getCookies();
obj.quit();
obj=new FirefoxDriver();
obj.get(“https://mail.google.com”);
for(Cookie cookie : allCookies){
obj.manage().addCookie(cookie);
}
}
}

Default Asked on October 6, 2016 in Selenium WebDriver.
Add Comment
  • 0 Answer(s)
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.