How To Add New Cookie When Executing Selenium WebDriver Test

Earlier we learnt how to extract and print current domain cookie during test execution using selenium WebDriver In previous post. Sometimes you have a requirement like you have to add new cookie for website under test during selenium WebDriver test execution for some kind of testing
purpose. Is It possible?

Yes, Selenium WebDriver has Inbuilt class named Cookie which contains many useful functions to play with cookie of website under test. You can create new cookie with your desired name and value and then you can use addCookie method to add new cookie In browser for your test domain. Syntax to add new cookie Is as bellow.

//Set cookie value and then add It for current domain.
Cookie name = new Cookie("testCookie", "WSfed-ffsd-234DFGe-YUTYU");
driver.manage().addCookie(name);

Full example to add new cookie and then print It In console to verify that new added cookie Is proper or not Is as bellow.

Note : Add URL of your website under test In bellow given example.

package Testing_Pack;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class addCookies {
 WebDriver driver;
 
 @BeforeTest
 public void setup() throws Exception {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("Your test site URL");
 }
 
 @Test
 public void addCookie(){
  //Set cookie value and then add It for current domain.
  Cookie name = new Cookie("testCookie", "WSfed-ffsd-234DFGe-YUTYU");
  driver.manage().addCookie(name);
  
  //Get all cookies and print them.
  Set<Cookie> totalCookies = driver.manage().getCookies();
  System.out.println("Total Number Of cookies : " +totalCookies.size());
  
  for (Cookie currentCookie : totalCookies) {
      System.out.println(String.format("%s -> %s -> %s", "Domain Name : "+currentCookie.getDomain(), "Cookie Name : "+currentCookie.getName(), "Cookie Value : "+currentCookie.getValue()));
  }  
 }
}

It will add new cookie for your test domain and then all cookies will be printed In console. Read next post to know how to delete cookie.

1 comment: