Automation QA Testing Course Content

Selenium Interview Questions

☒Automation:☒
1.What is xpath and it's types?
2.What is cross browser testing and parallel testing?
3.Challenges faced during selenium testing?
4.What is Actions class?
5.How to handle drop down in selenium?
6.How to handle multiple browser pop up?
7.How to handle multiple browser tabs in selenium?
8.How to perform upload file using selenium?
9.How to perform download file using selenium?
10.How to get all values of dropdown in selenium?
11.How to perform (control + a) through selenium?
12.How to shift between tabs of a same browser using selenium?
13.What is Robot class?
14.What is AutoIT?
15.What are the difference between get() and navigate()?
16.What are the difference between findElement() and findElements()?
17.What is difference between quit() and close()?
18.What are different locators used?
19.Difference between xpath and cssSelector?
20.Different approaches to click the submit button?
21.What is javascriptExecutor and when it is used?
22.Handling WebTable(static and dynamic) in selenium 
23.What is POM? Advantage and its disadvantage?
24.What is maven? list its phases or life cycle?Command to run our project thro maven?
25.Explain ur project folder structure? Or Explain ur frame work?
26.What is testng?
27.How to create and delete cookies?
28.What does getwindowhandles() and getwindowhandle() return? Or its differences?
29.Is it possible to use only perform() without build()? 30.What is perform() and build()?
31.How to scroll the browser window?
32. Preceding sibling and following sibling of custom xpath?
33.What is test management tool used in ur project?
34.What is the build automation tool used in ur project?
35.How u will handle the SSL certification?
Or what is DesiredCapabilities?
36.How to verify 'Bangalore' present in dropdown box or not?
37.How to verify 'Bangalore' present in 4×4 webtable? And print the column and row number of it is present?
38.How to fetch the data from particular row and column of excel?
39.List all maven plugins like surefire plugin etc
40.What is jenkins?And explain its use?
41.Explain the tags present in testng.xml file
42.What is TDD?
43.What is BDD? Explain cucumber framework?What is gherkins?
44.What is Listener?
45.What is DataProvider?
46.What is parameterization?
47.What is PageFactory?
48.What is apache POI API? Or how to read data from excel?
49.What is explicit and implicit waits?
50.What are the challenges faced in automation testing?
51.Write code for handling multiple browsers and switch to new windows?
52.What is webdriver?And why webdriver is used?
53.List some selenium exceptions
54.What is StaleElementReferenceException?When this occurs?And how to overcome such exception?
55.How do you group the test cases? And why?
56.How to include or exclude test cases?
57.What is NullPointerException?When it occurs?
58.What is selenium grid?
59.Should have knowledge on all testng annotations.
60.How do you control the execution of your test cases/test classes?
61.Git and its commands
62.Maven commands to execute,debug,compile
63.What is the current version of maven used?
64.How to identify broken links?How you have done in your project?Write code or tell approach.
65.Write a code to fetch the value 'Test' from excel sheet which might be present in any cell in excel. Or check whether value 'Test' is present in excel or not.
66.How to pass values to textbox other than using sendKeys()?
67.How to click login button other than using click(), submit() and JavascriptExecutor?
68.What is subversion?

Validating top 35 inspirational movies in IMDB website using Selenium WebDriver

package linkprograms;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Top35InspirationalMovieTest {

public static void main(String[] args) throws InterruptedException {
//set the chromedriver.exe path
System.setProperty("webdriver.chrome.driver", "D:\\webdriverjars\\executables\\chromedriver_win32\\chromedriver.exe");
//interface refobj=new implementingclass();
WebDriver driver=new ChromeDriver();
//open the google.com
driver.navigate().to("https://www.imdb.com/list/ls000632473/");
//maximize the window
driver.manage().window().maximize();
//add implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//create object for WebDriverWait class
WebDriverWait wait=new WebDriverWait(driver,30);

//fetch all the movie links from top inspirational movies section using findElemnts API
List<WebElement>top35inspLinksList=driver.findElements(By.xpath("//div[@class='lister-item-content']"));

for(int i=1;i<=top35inspLinksList.size();i++) {
System.out.println("************************************************");
//fetch the movie link name
String movielinkName=driver.findElement(By.xpath("//*[@id='main']/div/div[3]/div[3]/div["+i+"]/div[2]/h3/a")).getText();
System.out.println("link name is -->"+movielinkName);
//fetch the url of the each link
String movielinkurl=driver.findElement(By.xpath("//*[@id='main']/div/div[3]/div[3]/div["+i+"]/div[2]/h3/a")).getAttribute("href");
System.out.println(movielinkName+" url is-->"+movielinkurl);
//click on each link
driver.findElement(By.xpath("//*[@id='main']/div/div[3]/div[3]/div["+i+"]/div[2]/h3/a")).click();
if(driver.getTitle().contains(movielinkName)) {
System.out.println("correct movie page is displayed for the link:"+driver.getTitle());
}else {
System.out.println("correct page is not displayed"+driver.getTitle());
}
//naviagte to previous page
driver.navigate().back();

}
Thread.sleep(3000);
//close the browser
driver.close();
}

}

Broken Links Code by StatusCode

package linkprograms;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class BrokenLinksTest {

static WebDriver driver = null;
static WebDriverWait wait = null;

public static void main(String[] args) throws InterruptedException, IOException {
// 1 set the chromdriver.exe file path System.setproperty(p1,p2)

System.setProperty("webdriver.gecko.driver",
"D:\\webdriverjars\\executables\\gecko30\\geckodriver-v0.30.0-win64\\geckodriver.exe");

// Create Object for FirefoxOptions class
FirefoxOptions opt = new FirefoxOptions();

opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");

// interface variablename=new classname();
WebDriver driver = new FirefoxDriver(opt);
// maximize the window
driver.manage().window().maximize();

// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

// create WebDriverWaitobject
wait = new WebDriverWait(driver, Duration.ofMillis(30000));
// open the rediff.com
driver.get("https://makemysushi.com/404");

// fetch all the links into List using findelements locator -tagName -a
List<WebElement> linksList = driver.findElements(By.tagName("a"));
// this is final list after removing some other links
List<String> ls = new ArrayList();
// iterating the collection to add each link to the new collection that is ls
for (WebElement e : linksList) {
String url = e.getAttribute("href");
// adding each link url to the list collection
ls.add(url);

}
// removing unwanted urls from the collection using removeAll()
ls.removeAll(Arrays.asList(null, "mailto:info@makemysushi.com"));
// validate each link by validateLinks()
for(String l:ls) {
verifyLinks(l);
}
Thread.sleep(2000);
//close the browser
driver.quit();
}

private static void verifyLinks(String url) throws IOException {
// step1. Create object for URL class
URL ul = new URL(url);

// step2:
HttpURLConnection hc = (HttpURLConnection) ul.openConnection();

// step3 connect to the url
hc.connect();

// step4 - fetch the responseStatusCode & respmessage
int respCode = hc.getResponseCode();
// fetch respMessage
String respMsg = hc.getResponseMessage();
if (respCode == 200) {
System.out.println(url+ " link is working fine:" + respCode + " respMsg:" + respMsg);
} else if (respCode == 404) {
System.out.println(url+ " link is broken/not working fine:" + respCode + " respMsg:" + respMsg);
}

// step5 -disconnect to the URL
hc.disconnect();
}

}

Particular Section links Validation using Selenium WebDriver

package linksprograms;

import java.time.Duration;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import io.netty.handler.timeout.TimeoutException;

public class LinkedinSectionLinksTest {

static WebDriver driver = null;

public static void main(String[] args) throws InterruptedException {
// set the chromedriver.exe file path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome971\\chromedriver_win32\\chromedriver.exe");
// interface refvar=new implementedclass();
driver = new ChromeDriver();

// maximize the window
driver.manage().window().maximize();

// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));

// open the url in browser
driver.get("https://www.linkedin.com/");

// create Object for WebDriverWait class
WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(30000));

wait.until(ExpectedConditions.titleContains("LinkedIn: Log In or Sign Up"));
try {
// identify the General section
WebElement genSection = driver
.findElement(By.xpath("//div[contains(@class,'w-full flex justify-end')]/div[1]/ul"));
// fetch all the links from General section
List<WebElement> secLinksList = genSection.findElements(By.tagName("a"));
for (int i = 1; i <= secLinksList.size(); i++) {
System.out.println("***************************************************************");
// 1. get the text of each link --use getText();
String linkName = driver
.findElement(
By.xpath("//div[contains(@class,'w-full flex justify-end')]/div[1]/ul/li[" + i + "]/a"))
.getText();
System.out.println("link text is:" + linkName);
// 2.fetch each link url --use
String url = driver
.findElement(
By.xpath("//div[contains(@class,'w-full flex justify-end')]/div[1]/ul/li[" + i + "]/a"))
.getAttribute("href");
System.out.println(linkName + " link url is:" + url);
// 3.click on each link
driver.findElement(
By.xpath("//div[contains(@class,'w-full flex justify-end')]/div[1]/ul/li[" + i + "]/a"))
.click();
wait.until(ExpectedConditions.urlContains(driver.getCurrentUrl()));
System.out.println(linkName + " page title is:" + driver.getTitle());
// navigate back to home page
driver.navigate().back();
Thread.sleep(2000);
}
} catch (TimeoutException te) {
te.printStackTrace();
} finally {
// close the browser
if (driver != null) {
driver.quit();
}
}
}

}


Broken images code by Status Code using Selenium WebDriver

package linkprograms;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class BrokenImagesTest {

static WebDriver driver = null;
static WebDriverWait wait = null;

public static void main(String[] args) throws InterruptedException, IOException {
// 1 set the chromdriver.exe file path System.setproperty(p1,p2)

System.setProperty("webdriver.gecko.driver",
"D:\\webdriverjars\\executables\\gecko30\\geckodriver-v0.30.0-win64\\geckodriver.exe");

// Create Object for FirefoxOptions class
FirefoxOptions opt = new FirefoxOptions();

opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");

// interface variablename=new classname();
WebDriver driver = new FirefoxDriver(opt);
// maximize the window
driver.manage().window().maximize();

// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

// create WebDriverWaitobject
wait = new WebDriverWait(driver, Duration.ofMillis(30000));
// open the rediff.com
driver.get("http://the-internet.herokuapp.com/");
//click on Broken Images link
driver.findElement(By.linkText("Broken Images")).click();
//wait for the Borken Images heading element
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[class='example']>h3")));

// fetch all the images into List using findElements locator -tagName -img
List<WebElement> imagesList = driver.findElements(By.tagName("img"));
//iterate all the images using for each loop
for(WebElement img:imagesList) {
String imgsrc=img.getAttribute("src");
verifyLinks(imgsrc);
}
Thread.sleep(2000);
//close the browser
driver.quit();
}

private static void verifyLinks(String url) throws IOException {
// step1. Create object for URL class
URL ul = new URL(url);

// step2:
HttpURLConnection hc = (HttpURLConnection) ul.openConnection();

// step3 connect to the url
hc.connect();

// step4 - fetch the responseStatusCode & respmessage
int respCode = hc.getResponseCode();
// fetch respMessage
String respMsg = hc.getResponseMessage();
if (respCode == 200) {
System.out.println(url+ " link is working fine:" + respCode + " respMsg:" + respMsg);
} else if (respCode == 404) {
System.out.println(url+ " link is broken/not working fine:" + respCode + " respMsg:" + respMsg);
}

// step5 -disconnect to the URL
hc.disconnect();
}

}

Broken images

package linkprograms;

package linkspograms;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrokenLinksTest {

private static WebDriver driver;

public static void main(String[] args) throws InterruptedException, IOException {
// set the chromedriver.exe path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome92\\chromedriver_win32\\chromedriver.exe");
// interface refvar = new browserclass();
WebDriver driver = new ChromeDriver();

// maxmize the window
driver.manage().window().maximize();

// add implicitwait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// open the https://makemysushi.com/404 website
driver.get("https://makemysushi.com/404");
List<String>ls=new ArrayList();
//fetch all the links in a browser
List<WebElement>linkList=driver.findElements(By.tagName("a"));
for(WebElement e:linkList) {
String url=e.getAttribute("href");
//adding each link url to the list collection
ls.add(url);
}
//removing unwanted urls from the collection using removeAll()
ls.removeAll(Arrays.asList(null,"mailto:info@makemysushi.com"));
//validate each link by validateLinks()
for(String s:ls) {
validateLinks(s);
}
//close the browse
driver.close();
}
private static void validateLinks(String url) throws IOException {
//create Object for URL class
URL ul = new URL(url);
HttpURLConnection hc= (HttpURLConnection) ul.openConnection();
//connect to the url
hc.connect();
//fetch the status code of the url
int respStatusCode=hc.getResponseCode();
String respMsg=hc.getResponseMessage();
if(respStatusCode==200) {
System.out.println(url+" is working fine:"+respStatusCode+" "+respMsg);
}else if(respStatusCode==404) {
System.out.println(url+" is not working/broken:"+respStatusCode+" "+respMsg);
}
//disconnect from the url
hc.disconnect();
}

}




Actions class Usage in Selenium WebDriver

Actions Class: It is mainly used to handle mouse and keyboard actions.
package:org.openqa.selenium.interactions

Action build()
Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).
Actions click():
Clicks at the current mouse location.
Actions click(WebElement onElement)
Clicks in the middle of the given element.
Actions clickAndHold()
Clicks (without releasing) at the current mouse location.
Actions clickAndHold(WebElement onElement)
Clicks (without releasing) in the middle of the given element.
Actions contextClick()
Performs a context-click at the current mouse location.
Actions contextClick(WebElement onElement)
Performs a context-click at middle of the given element.
Actions doubleClick()
Performs a double-click at the current mouse location.
Actions doubleClick(WebElement onElement)
Performs a double-click at middle of the given element.
Actions dragAndDrop(WebElement source, WebElement target)
A convenience method that performs click-and-hold at the location
of the source element, moves to the location of the target element,
then releases the mouse.
Actions dragAndDropBy(WebElement source, int xOffset, int yOffset)
A convenience method that performs click-and-hold at the
location of the source element, moves by a given offset,
then releases the mouse.
Actions keyDown(Keys.keyName)
Performs a modifier key press.
Actions keyDown(WebElement element, Keys.keyname)
Performs a modifier key press after focusing on an element.
Actions keyUp(Keys.Keyname)
Performs a modifier key release.
Actions keyUp(WebElement element, Keys.Keyname)
Performs a modifier key release after focusing on an element.
Actions moveByOffset(int xOffset, int yOffset)
Moves the mouse from its current position (or 0,0) by the given offset.
Actions moveToElement(WebElement toElement)
Moves the mouse to the middle of the element.
Actions moveToElement(WebElement toElement, int xOffset, int yOffset)
Moves the mouse to an offset from the top-left corner of the element.

void perform()
A convenience method for performing the actions without calling build() first.
Actions release()
Releases the depressed left mouse button at the current mouse location.
Actions release(WebElement onElement)
Releases the depressed left mouse button, in the middle of the given element.
Actions sendKeys(java.lang.CharSequence... keysToSend)
Sends keys to the active element.
Actions sendKeys(WebElement element, keys.keyname)
Equivalent to calling: Actions.click(element).sendKeys(keysToSend). This method is different from WebElement.sendKeys(CharSequence...) - see sendKeys(CharSequence...) for details how.

//create an object for Actions class and pass the browser ref to the object.
Actions act=new Actions(driver);

calling the Actions class methods
refcvar.methodname().perform();

if you are performing multiple actions on the same element
build():Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).
1)create an object for Actions class
Actions act=new Actions(driver);

Action actionrefvar=act.method1().method2().method3().method4().build();
 
actionrefvar.perform();
===============================================================
ACTIONS CLASS PROGRAMS :
-----------------------------------------------------------------------------------------------------------
Program1: DRAG AND DROP TEST:
/**
 * 1)open the https://jqueryui.com/droppable/
 * 2)switch to iframe
 * 3)identify the source & target elements
 * 4)create object for Actions class
 * 5)then call dragAndDropBy(src,xcoordi,ycoordi).perform()
 * @throws InterruptedException
 */
---------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.asserts.Assertion;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;

public class DragAndDropTest {
private WebDriver driver = null;
private WebDriverWait wait = null;
/**
 * 1)open the https://jqueryui.com/droppable/
 * 2)switch to iframe
 * 3)identify the source & target elements
 * 4)create object for Actions class
 * 5)then call dragAndDrop(src,tgt).perform()
 * @throws InterruptedException
 */
@Test
public void autoSuggestionBykeysTest() throws InterruptedException {
// open the google.com
driver.get("https://jqueryui.com/droppable/");
wait.until(ExpectedConditions.titleIs("Droppable | jQuery UI"));
//switch to Iframe
driver.switchTo().frame(0);
//driver.switchTo().frame(driver.findElement(By.className("demo-frame")));
//identify the source
WebElement src=driver.findElement(By.id("draggable"));
//identify the target element
WebElement tgt=driver.findElement(By.id("droppable"));
//create object for Actions class
Actions act = new Actions(driver);
//drag the source element to target element then release
//act.dragAndDrop(src, tgt).perform();
//click and hold the source element
act.clickAndHold(src).perform();
//move the source element to target element
act.moveToElement(tgt).perform();
//release the mouse at target element
act.release().perform();
Thread.sleep(3000);
}

@Parameters({ "browser" }) @BeforeClass public void setUp(String browser) { Reporter.log("started executing the @BeforeClass", true); if (browser.equalsIgnoreCase("chrome")) { ChromeOptions opt = new ChromeOptions(); opt.setAcceptInsecureCerts(true); driver = new ChromeDriver(opt); Reporter.log("chromebrowser is launched", true); } else if (browser.equalsIgnoreCase("firefox")) { FirefoxOptions opt = new FirefoxOptions(); opt.setAcceptInsecureCerts(true); // interface refvar=new implementedclass(); driver = new FirefoxDriver(opt); Reporter.log("firefox browser is launched", true); } else if (browser.equalsIgnoreCase("edge")) { EdgeOptions opt = new EdgeOptions(); opt.setAcceptInsecureCerts(true); driver = new EdgeDriver(opt); } Reporter.log("edge browser is launched", true); Reporter.log("maximize the window", true); driver.manage().window().maximize(); Reporter.log("add implicitwait", true); driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000)); Reporter.log("add explicitwait object", true); wait = new WebDriverWait(driver, Duration.ofSeconds(30)); Reporter.log("creating Object for WebDriverUtils class", true); wutils = new WebDriverUtils(driver); }

@AfterClass
public void afterClass() {
// close the browser
driver.close();
}

}


======================================================================
PROGRAM 2: DRAG AND DROPBY PROGRAM:
/**
 * 1)open the https://jqueryui.com/draggable/
 * 2)switch to iframe
 * 3)identify the source & target elements
 * 4)create object for Actions class
 * 5)then call dragAndDropBy(src,xcoord,ycoordinates).perform()
 * @throws InterruptedException
 */
-------------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.asserts.Assertion;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;

public class DragAndDropByTest {
private WebDriver driver = null;
private WebDriverWait wait = null;

@Test
public void dragAndDropByTest() throws InterruptedException {
// open the google.com
driver.get("https://jqueryui.com/draggable/");
wait.until(ExpectedConditions.titleIs("Draggable | jQuery UI"));
//switch to Iframe
//driver.switchTo().frame(0);
driver.switchTo().frame(driver.findElement(By.className("demo-frame")));
//identify the source
WebElement src=driver.findElement(By.id("draggable"));
//create object for Actions class
Actions act = new Actions(driver);
//drag the source element to x,y coordinate place
act.dragAndDropBy(src,100,120).perform();
//click and hold the source element
/*act.clickAndHold(src).perform();
//move the source element to target element
act.moveByOffset(100, 120).perform();
//release the mouse at target element
act.release().perform();*/
Thread.sleep(3000);
}

@Parameters({ "browser" })
@BeforeClass
public void setUp(String browser) {
Reporter.log("started executing the @BeforeClass", true);
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt = new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt = new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt = new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
}
Reporter.log("edge browser is launched", true);
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}

@AfterClass
public void afterClass() {
// close the browser
driver.close();
}

}
=====================================================================
PROGRAM 3: MENU HANDLING:
/**
 * 1)open the https://jqueryui.com/menu/
 * 2)switch to iframe
 * 3)identify the music menu element
 * 4)create object for Actions class
 * 5)then call moveToElement(musicmenu).perform();
 6)wait for the rockSubMenu element --then movetoraocksubmenu
5)wait for the classicsubmenu and click on classic submenu
 * @throws InterruptedException
 */

--------------------------------------------------------------------------------------------------
package testngprograms;
import org.testng.annotations.Test;
import org.testng.asserts.Assertion;
import org.testng.asserts.SoftAssert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;

public class MenuHandlingTest {
WebDriver driver=null;
WebDriverWait wait=null;
  @Test
  public void menuHandlingyTest() throws InterruptedException {
  //create Object for SoftAssert class
  SoftAssert sa=new SoftAssert();
  //open the url
  driver.get("https://jqueryui.com/menu/");
  wait.until(ExpectedConditions.titleContains("Menu | jQuery UI"));
  sa.assertTrue(driver.getPageSource().contains(driver.getTitle()));
  //switch to iframe based on position
  driver.switchTo().frame(0);
  
  //Create Object for Actions class
  Actions act=new Actions(driver);
//identify the Music menu
  WebElement musicMenu=driver.findElement(By.id("ui-id-9"));
  sa.assertTrue(musicMenu.isDisplayed(),"music menu is not available");  
  //move to the About element
  act.moveToElement(musicMenu).perform();
  
//identify the Music menu
  WebElement rockSubMenu=driver.findElement(By.id("ui-id-10"));
  
  wait.until(ExpectedConditions.visibilityOf(rockSubMenu));
  sa.assertTrue(rockSubMenu.isDisplayed(),"rocksubmenu is not available");
  //move to the About element
  act.moveToElement(rockSubMenu).perform();
  
//identify the Music ->rock-->classic submenu
  WebElement classicSubMenu=driver.findElement(By.id("ui-id-12"));
  
  wait.until(ExpectedConditions.visibilityOf(classicSubMenu));
  sa.assertTrue(classicSubMenu.isDisplayed(), "classic SubMenu is not available");
  //move to the About element
// act.moveToElement(classicSubMenu).perform();
  act.click(classicSubMenu).perform();
  sa.assertAll();
  Thread.sleep(3000);
  
  }
  @Parameters({ "browser" })
@BeforeClass
public void setUp(String browser) {
Reporter.log("started executing the @BeforeClass", true);
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt = new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt = new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt = new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
}
Reporter.log("edge browser is launched", true);
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}

@AfterClass
public void afterClass() {
// close the browser
driver.close();
}
}

--------------------------------------------------------------------------------------------
Handling FlipKart menu
1)open the flipkart.com
2)verify the page title
3)if sign in popup appears close it
4)open electronics main menu
5)mouse over on laptops and desktops submenu
6)click on laptops submenu
-----------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;

import basicprograms.WebDriverUtils;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;

public class FlipKartMenuHandlingTest {
WebDriver driver = null;
WebDriverWait wait = null;
WebDriverUtils wutils = null;

@Test
public void menuHandlingTest() throws InterruptedException {
Reporter.log("Started executing the menuHandlingTest", true);
Reporter.log("Open https://www.flipkart.com/ in the browser", true);
driver.get("https://www.flipkart.com/");
Reporter.log("wait for Online Shopping Site flipkart UI home page title", true);
wait.until(ExpectedConditions.titleContains("Online Shopping Site"));
Reporter.log("asserting the Online Shopping Site UI page title", true);
Assert.assertTrue(driver.getTitle().contains("Online Shopping Site"), "flipkart title is not loaded");
if(driver.findElement(By.xpath("//*[@class='_2Sn47c']/div/div/button")).isDisplayed()) {
wutils.highLightElement1(driver, driver.findElement(By.xpath("//*[@class='_2Sn47c']/div/div/button")));
wutils.safeJavaScriptClick(driver, driver.findElement(By.xpath("//*[@class='_2Sn47c']/div/div/button")));
}
Reporter.log("Create Object for Actions class ", true);
Actions act = new Actions(driver);
Reporter.log("identify the source element ", true);
WebElement electronicsMenu = driver.findElement(By.xpath("//div[@class='xtXmba'][contains(.,'Electronics')]"));
Reporter.log("Mouse over on Electronics main menu element ", true);
wutils.highLightElement1(driver, electronicsMenu);
act.moveToElement(electronicsMenu).perform();
WebElement laptopAndDesktopSubMenuOptin = driver.findElement(By.xpath("//*[starts-with(text(),'Laptop and Desktop')]"));
Reporter.log("Move the mouse to given x n y coordinates", true);
wait.until(ExpectedConditions.visibilityOf(laptopAndDesktopSubMenuOptin));
Thread.sleep(1000);
wutils.highLightElement1(driver, laptopAndDesktopSubMenuOptin);
act.moveToElement(laptopAndDesktopSubMenuOptin).perform();
WebElement laptopSubMenuOptin = driver.findElement(By.xpath("//a[starts-with(text(),'Laptops')]"));
Reporter.log("wait for the visibility of Laptops", true);
Thread.sleep(1000);
wait.until(ExpectedConditions.visibilityOf(laptopSubMenuOptin));
wutils.highLightElement1(driver, laptopSubMenuOptin);
Reporter.log("click on laptopSubMenuOptin element ", true);
wutils.safeJavaScriptClick(driver,laptopSubMenuOptin);
wait.until(ExpectedConditions.titleContains("Laptops - Biggest Deals on Laptops Online"));

Thread.sleep(2000);
}

@Parameters({ "browser" })
@BeforeClass
public void setUp(String browser) {
Reporter.log("started executing the @BeforeClass", true);
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt = new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt = new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt = new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
}
Reporter.log("edge browser is launched", true);
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}

@AfterClass(alwaysRun = true)
public void afterClass() {
Reporter.log("started executing the @AfterClass", true);
Reporter.log("close the browser", true);
if (driver != null) {
driver.quit();
}
}
}


====================================================================
PROGRAM 4: MULTIPLEACTIONS PROGRAM

/**1)open the linkedin.com website url
  2)click on sign in link
3)wait for the sing in page title
4)identify the emaileditbox
5)create object for Actions class
6)call click() on emaileditbox then press the SHIFT key-->then type the selenium keyword in emaileditbox-->then release the SHIFT key-->then perform doublclick operation on emaileditbox-->then perform rightclick operation**/
----------------------------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.asserts.Assertion;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;

public class MultipleActionsOnLinkedinPagetest {
private WebDriver driver=null;
private WebDriverWait wait=null;
  @Test
  public void compositeActionsTest() throws InterruptedException {
  //open the url
  driver.navigate().to("http://linkedin.com/home");
  wait.until(ExpectedConditions.titleContains("LinkedIn: Log In or Sign Up"));
  
  //click on Sign in link
  driver.findElement(By.linkText("Sign in")).click();
  
  wait.until(ExpectedConditions.titleContains("LinkedIn Login, Sign in | LinkedIn"));
  
  //identify the email editbox
  WebElement email_editbox=driver.findElement(By.id("username"));
    
  //create an object for Actions class
  Actions act=new Actions(driver);
  
  //composite actions
  Action cmpActions=act.click(email_editbox)
               .keyDown(Keys.SHIFT)
               .sendKeys(email_editbox, "selenium")
               .keyUp(Keys.SHIFT)
               .doubleClick(email_editbox)
               .contextClick().build();
  cmpActions.perform();
  Thread.sleep(3000);
  }
  @Parameters({ "browser" })
@BeforeClass
public void setUp(String browser) {
Reporter.log("started executing the @BeforeClass", true);
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt = new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt = new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt = new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
}
Reporter.log("edge browser is launched", true);
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}
@AfterClass
public void afterClass() {
// close the browser
driver.close();
}
}

===============================================================
PROGRAM5: Open link in new tab and new window using Keys enum chord()
/**
open google.com
identify the about link
create tab and new window strings using Keys enum chord()
**/
---------------------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.asserts.Assertion;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;

public class RightClickOperationTest {
WebDriver driver=null;
WebDriverWait wait=null;
  @Test
  public void rightClickOperationTest() throws InterruptedException {
  //open the url
  driver.get("https://google.com/");
  wait.until(ExpectedConditions.titleContains("Google"));
  Assert.assertTrue(driver.getPageSource().contains(driver.getTitle()));
  //identify the About element
  WebElement aboutLink=driver.findElement(By.linkText("About"));
  String tab=Keys.chord(Keys.CONTROL,Keys.RETURN);
  
  String newWindow=Keys.chord(Keys.SHIFT,Keys.ENTER);
  //openning link in new tab
  aboutLink.sendKeys(tab);
  
  Thread.sleep(5000);
  
  
  aboutLink.sendKeys(newWindow);
  
/* //Create Object for Actions class
  Actions act=new Actions(driver);
  //1.move to the About element
  act.moveToElement(aboutLink).perform();
  
Thread.sleep(5000);
  
  }

@Test(description="linkedin home page Test")
public void openLinkInNewTabAndNewWindow() throws InterruptedException {
Reporter.log("open the linkedin url");
driver.get("https://linkedin.com");
Reporter.log("Verify Linkedin Home page title ", true);
wait.until(ExpectedConditions.titleIs("LinkedIn: Log In or Sign Up"));
Reporter.log("asserting the LinkedIn: Log In or Sign Up page title", true);
Assert.assertEquals(driver.getTitle(), "LinkedIn: Log In or Sign Up");
Reporter.log("wait for the linkedin logo ", true);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(@class,'nav__logo-link')]")));
WebElement signinLink=driver.findElement(By.xpath("//a[@class='nav__button-secondary btn-md btn-secondary-emphasis']"));
if(signinLink.isDisplayed()&&signinLink.isEnabled()) {
Reporter.log("click on sign in link ", true);
signinLink.click();
}
WebElement userNameEditbox=driver.findElement(By.id("username"));
Reporter.log("clear the content in username editbox", true);
userNameEditbox.clear();
//type without sendkeys method
wutils.setAttribute(userNameEditbox, "value", "seleniumwebdriver");
//highlight the element
wutils.highLightElement1(driver, userNameEditbox);
//identify the forgot password
WebElement forgotPassword=driver.findElement(By.cssSelector("a.btn__tertiary--medium.forgot-password"));
//tab
String tab=Keys.chord(Keys.CONTROL,Keys.RETURN);
//new window
String newWindow=Keys.chord(Keys.SHIFT,Keys.ENTER);
//opening the link in new tab
forgotPassword.sendKeys(tab);
Thread.sleep(2000);
//opening the link in new window
forgotPassword.sendKeys(newWindow);
Thread.sleep(2000);
}

@Test
public void openNewTabAndNewWindow() throws InterruptedException {
//open the new tab and switch to it open any url inthat tab
driver.switchTo().newWindow(WindowType.TAB);
//open the url
driver.navigate().to("https://facebook.com");
Thread.sleep(2000);
//open new window and switch to it
driver.switchTo().newWindow(WindowType.WINDOW);
//open the url in new window
driver.navigate().to("https://amazon.in");
Thread.sleep(2000);
}
@Parameters({"browser"})
@BeforeClass(alwaysRun=true)
public void beforeClass(String browser) {
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt=new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt=new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
//opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt=new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
Reporter.log("edge browser is launched", true);
}
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}

@AfterClass(alwaysRun=true)
public void afterClass() {
Reporter.log("started executing the @AfterClass", true);
Reporter.log("close the browser", true);
if (driver != null) {
driver.quit();
}
}

  

}
=========================================================================
PROGRAM6: HighlightTypeWithoutSendKeysand performJavascriptClick
/**
open the amazon.in
identify the searcheditbox
highlight the searcheditbox and type headphones keyword without sendkeys()
send ENTER key to the searcheditbox using Actions class
Press PAGEDWON & PAGEUP keys using Actions class
then scroll for the backtotop element
click on backtoTop element using javascriptClick

*/

 
-----------------------------------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;

public class HighLightTypeWoSendKeysTest {
private WebDriver driver=null;
private WebDriverWait wait=null;
  @Test
  public void highlightAndTypeWoSendKeysTest() throws InterruptedException {
  //ope nthe url
  driver.navigate().to("http://amazon.in");
  wait.until(ExpectedConditions.titleContains("Amazon.in"));
  //create an object for Actions class
  Actions act=new Actions(driver);
    
//identify the search editbox
  WebElement srch_editbox=driver.findElement(By.id("twotabsearchtextbox"));
  //highlight the element
  Utility.highLightElement1(driver, srch_editbox);
  //type the value in search editbox
  Utility.setAttribute(srch_editbox, "value", "headphones");
  //Press Enter key on the element
  srch_editbox.sendKeys(Keys.ENTER);
 
  //press PAGEDOWN from keywboard
  act.sendKeys(Keys.PAGE_DOWN).perform();
  Thread.sleep(3000);
  act.sendKeys(Keys.PAGE_UP).perform();
  Thread.sleep(5000);
  //scroll for element
  WebElement backTotop=driver.findElement(By.id("navBackToTop"));
  Utility.scrollForElement(driver, backTotop);
  Thread.sleep(3000);
  //perform click action using javascript click
  Utility.safeJavaScriptClick(driver, backTotop);
  
  Thread.sleep(3000);
  
  }
  @Parameters({"browser"})
@BeforeClass(alwaysRun=true)
public void beforeClass(String browser) {
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt=new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt=new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
//opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt=new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
Reporter.log("edge browser is launched", true);
}
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}
  @AfterClass
  public void afterClass() {
  Reporter.log("i am inside the @AfterClass ...");
  System.out.println("started executing the @AfterClass ..");
  if(driver!=null) {
  driver.close();
  }
  System.out.println("Ended executing the @AfterClass ..");
  }


}
=========================================================================
PROGRAM7:HANDLING WEB TABLES

/*
*
  • Open the browser
  • Load the page:https://the-internet.herokuapp.com/
  • click on Sortable Data Tables link
  • Click the column heading
  • Grab the values for the column
  • fetch all the rows then fetch all the columns for each row
  • Close the browser
*
*
*/
---------------------------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.number.OrderingComparison.lessThan;
import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo;
import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;

public class HandlingTableTest {
WebDriver driver = null;
WebDriverWait wait = null;
@BeforeMethod
public void setupTest() {
driver.get("https://the-internet.herokuapp.com/");
wait.until(ExpectedConditions.titleContains("The Internet"));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h1.heading")));
String headerTxt = driver.findElement(By.cssSelector("h1.heading")).getText();
Assert.assertEquals("Welcome to the-internet", headerTxt);
// check whether Sortable Data Tables link is avaiable or not
try {
WebElement sortableTableLink = driver.findElement(By.partialLinkText("Sortable Data Tables"));
Assert.assertTrue(sortableTableLink.isDisplayed());
sortableTableLink.click();
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
  @Test
  public void handlingTable() {
//wait for the DataTable page
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.example > h3")));
//fetch all the columns
List<WebElement>columnsList=driver.findElements(By.xpath("//table[@id='table1']/thead/tr/th"));
System.out.println("no of columns in table:"+columnsList.size());
for(WebElement col:columnsList) {
System.out.println("column name is:"+col.getText());
}
//fetch all the rows in the table
List<WebElement>rowsList=driver.findElements(By.xpath("//table[@id='table1']//tbody/tr"));
System.out.println("no of rows in table:"+rowsList.size());
for(WebElement row:rowsList) {
System.out.println("Rows data "+row.getText());
}
System.out.println("***************************************************");
//iterate al lthe rows and columns
for(int i=1;i<=rowsList.size();i++) {
List<WebElement>columnsList1=driver.findElements(By.xpath("//table[@id='table1']/tbody/tr[1]/td"));
for(int j=1;j<=columnsList1.size();j++) {
System.out.println(i+"row "+j+" columns cell data:"+getTableCellData(i, j));
}
}
System.out.println("***************************************************");
/**
* //*[@id="table1"]/tbody/tr[2]/td[3]
* //*[@id="table1"]/tbody/tr[1]/td[3]
*/
System.out.println("cell data 2nd ow 3 col:"+getTableCellData(2,3));
System.out.println("cell data 3rd  ow 4 col:"+getTableCellData(3,4));
  }
  
  private String getTableCellData(int row,int col) {
String data=driver.findElement(By.xpath("//*[@id='table1']/tbody/tr["+row+"]/td["+col+"]")).getText();
return data;
  }
  
  @Test
  public void sortDueColumnInAscendingOrder() {
 
      driver.findElement(By.cssSelector("#table2 thead .dues")).click();
      List<WebElement> dues = driver.findElements(By.cssSelector("#table2 tbody .dues"));
      List<Double> dueValues = new LinkedList<Double>();
      for(WebElement element : dues){
          dueValues.add(Double.parseDouble(element.getText().replace("$", "")));
      }
      for(int counter = 0; counter < dueValues.size() - 1; counter++){
          assertThat(dueValues.get(counter), is(lessThanOrEqualTo(dueValues.get(counter + 1))));
      }
  
  }
  
  @Test
  public void withoutHelpfulMarkupDuesDescending() {
     

      driver.findElement(By.cssSelector("#table1 thead tr th:nth-of-type(4)")).click();
      driver.findElement(By.cssSelector("#table1 thead tr th:nth-of-type(4)")).click();

      List<WebElement> dues = driver.findElements(By.cssSelector("#table1 tbody tr td:nth-of-type(4)"));
      List<Double> dueValues = new LinkedList<Double>();
      for (WebElement element : dues) {
          dueValues.add(Double.parseDouble(element.getText().replace("$", "")));
      }

      for (int counter = 0; counter < dueValues.size() - 1; counter++) {
          assertThat(dueValues.get(counter), is(greaterThanOrEqualTo(dueValues.get(counter + 1))));
      }
  }
  
  @Test
  public void withoutHelpfulMarkupEmailAscending() {
    

      driver.findElement(By.cssSelector("#table1 thead tr th:nth-of-type(3)")).click();

      List<WebElement> emails = driver.findElements(By.cssSelector("#table1 tbody tr td:nth-of-type(3)"));
      for(int counter = 0; counter < emails.size() -1; counter++){
       assertThat(emails.get(counter).getText().compareTo(emails.get(counter + 1).getText()),is(lessThan(0)));
      }
  }
  
  
  @Parameters({"browser"})
@BeforeClass(alwaysRun=true)
public void beforeClass(String browser) {
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt=new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt=new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
//opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt=new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
Reporter.log("edge browser is launched", true);
}
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}
   @AfterClass
   public void afterClass() {
    System.out.println("I am in AfterClass block");
  //close the browser
  driver.close();
   }


}


======================================================================
PROGRAM8: select the date from calender for current month

-------------------------------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

public class JqueryDatePickerTest {
WebDriver driver = null;
WebDriverWait wait = null;

@Test
public void dateSelectionTest() throws InterruptedException {

driver.get("http://jqueryui.com/datepicker/");

//switch to iframe
WebElement frameElement = driver.findElement(By.className("demo-frame"));
driver.switchTo().frame(frameElement);
// click to open the date time picker calendar.
By dtp = By.xpath("//*[@id='datepicker']");
wait.until(ExpectedConditions.presenceOfElementLocated(dtp));
driver.findElement(dtp).click();

// Provide the day of the month to select the date.
HandleJQueryDateTimePicker("29");
Thread.sleep(3000);
}

// Function to select the day of the month in the date picker.
private void HandleJQueryDateTimePicker(String day) throws InterruptedException {

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("ui-datepicker-div")));
WebElement table = driver.findElement(By.className("ui-datepicker-calendar"));
System.out.println("JQuery Calendar Dates");
// fetch all the rows in the table
List<WebElement> tableRows = table.findElements(By.xpath("//tr"));
for (WebElement row : tableRows) {
//fetch the all columns for each row
List<WebElement> cells = row.findElements(By.xpath("//td"));

for (WebElement cell : cells) {
if (cell.getText().equals(day)) {
driver.findElement(By.linkText(day)).click();
}
}
}

// Switch back to the default screen again and scroll up by using
// the negative y-coordinates.
driver.switchTo().defaultContent();
((JavascriptExecutor) driver).executeScript("scroll(0, -250);");

// Intentional pause for 2 seconds.
Thread.sleep(2000);
}

// Function to select the day of the month in the date picker.
private void HandleJQuerySelectMonthAndYear(String month,String year) throws InterruptedException {

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("ui-datepicker-div")));
WebElement table = driver.findElement(By.className("ui-datepicker-calendar"));
System.out.println("JQuery Calendar Dates");
String ActualMonthYearText=null;
String expectedMonthYearText=null;
do {
//fetch the currentmonth value
String monthVal=driver.findElement(By.className("ui-datepicker-month")).getText();
//fetch the current year value
String yearVal=driver.findElement(By.className("ui-datepicker-year")).getText();
if(!monthVal.equals(month)) {
//click on next/previous button
driver.findElement(By.xpath("//span[contains(.,'Next')]")).click();
}
ActualMonthYearText= monthVal+" "+yearVal;
expectedMonthYearText=month+" "+year;
if(ActualMonthYearText.equals(expectedMonthYearText)) {
//select the date method call 
}
}while(!ActualMonthYearText.equals(expectedMonthYearText));
// Switch back to the default screen again and scroll up by using
// the negative y-coordinates.
driver.switchTo().defaultContent();
((JavascriptExecutor) driver).executeScript("scroll(0, -250);");

// Intentional pause for 2 seconds.
Thread.sleep(2000);
}

@Parameters({"browser"})
@BeforeClass(alwaysRun=true)
public void beforeClass(String browser) {
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt=new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions opt=new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
//opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt=new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
Reporter.log("edge browser is launched", true);
}
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}
@AfterClass
public void afterTest() {
driver.close();
}

}
=========================================================================

Converting Texts to Uppercase

When we want to enter the text manually, we press down the SHIFT key and enter the text simultaneously without releasing the SHIFT key. We can apply the same logic to our code like below-

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class keysDemo {

@Test
public static void refreshThePageUsingActions() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver.manage().window().maximize();

WebElement element = driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div[1]/div[1]/div/div[2]/input"));

Actions action = new Actions(driver);

//holds the SHIFT key and converts the text to uppercase
action.keyDown(element,Keys.SHIFT).sendKeys("lambdatest").build().perform();
driver.quit();

}

}

=====================================

Refresh the page

Actions class in Selenium test automation can also be used to perform the basic operation of refreshing. This might not seem as useful but it does have its perks when a browser is not able to read the contents of a page in the first go.

Below is a sample code that can be used to refresh a web page-

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class refresh {

@Test
public static void refreshThePageUsingActions() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

driver.get("https://www.amazon.in");
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.manage().window().maximize();

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Actions action = new Actions(driver);

action.keyDown(Keys.CONTROL).sendKeys(Keys.F5).build().perform();

driver.quit();
}

}

==========================================================================================

Copy & Paste

Copying some text from the source and pasting them in a target location can also be done with the help of actions class in Selenium test automation. The logic is the same as how we copy and paste texts manually.

Below is the sample code for copying the text and pasting it in another location-

import static org.testng.Assert.assertEquals;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class copyPaste {
@Test
public static void copyAndPasteUsingActions() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

driver.get("https://www.google.com/account/about/");

driver.manage().window().maximize();

WebElement element = driver.findElement(By.xpath("//*[text() = 'Create an account']"));

element.click();
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);

WebElement firstName = driver.findElement(By.id("firstName"));
WebElement userName = driver.findElement(By.id("username"));

firstName.sendKeys("Ramesh");

Actions action = new Actions(driver);

action.keyDown( Keys.CONTROL ).sendKeys( "a" ).keyUp( Keys.CONTROL ).build().perform();
action.keyDown( Keys.CONTROL ).sendKeys( "c" ).keyUp( Keys.CONTROL ).build().perform();

userName.click();
action.keyDown( Keys.CONTROL ).sendKeys( "v" ).keyUp( Keys.CONTROL ).build().perform();
driver.close();
}
}

=====================================================================
  • Open the browser
  • Visit the page
  • Find the element and send the space key to it
  • Find the result text on the page and check to that it's what we expect
  • Send the left arrow key to the element that's currently in focus
  • Find the result text on the page and check to that it's what we expect
  • Close the browser
=======================================================================

Scroll Up & Down the page

You can also scroll to the top or the bottom of a page using the Actions class in Selenium test automation.

import static org.testng.Assert.assertEquals;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class Scroll {

@Test
public static void scrollUpAndDownUsingActions() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

driver.get("https://www.lambdatest.com/");

assertEquals(driver.getTitle(), "Most Powerful Cross Browser Testing Tool Online | LambdaTest");
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

Actions act = new Actions(driver);
// Scroll Down using Actions class
act.keyDown(Keys.CONTROL).sendKeys(Keys.END).perform();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Scroll Up using Actions class
act.keyDown(Keys.CONTROL).sendKeys(Keys.HOME).perform();

driver.close();
}

}