What Are Cookies?
- Cookies are small files which are stored on a user's computer.
- They are designed to hold a modest amount of data specific to a particular client and website, and can be accessed either by the web server or the client computer.
- This allows the server to deliver a page tailored to a particular user, or the page itself can contain some script which is aware of the data in the cookie and so is able to carry information from one visit to the website to the next.
- Cookies contains domain name for which it is created, Cookie name and its value.
- It also contains validity duration of cookie.
- Selenium 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 follow.
1 2 3 4 5 6 7 8 9 10 11 12 | //Set cookie value and then add It for current domain. Cookie ck = new Cookie("user", "vinod"); driver.manage().addCookie(ck); //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())); System.out.println("=> Domain Name : " + currentCookie.getDomain() + " => Cookie Name : " + currentCookie.getName() + " => Cookie Value : "+ currentCookie.getValue()); } |
1 2 3 4 5 6 7 8 9 | //Syntax for deleting specific cookie is as follow. driver.manage().deleteCookieNamed("user"); //Syntax for deleting all cookies is as follow. driver.manage().deleteAllCookies(); //Print number of cookies after deleting all cookies. Set<Cookie> totalCookies = driver.manage().getCookies(); System.out.println("Total Number Of cookies after delete all cookies : " + totalCookies.size()); |
No comments:
Post a Comment