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();
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();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.