You are on page 1of 35

1

Login Rediffmail:

package Automation;

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

public class LoginRefdifmail {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\


BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://mail.rediff.com/cgi-bin/login.cgi");
//driver.findElement(By.id("login1")).sendKeys("anees");
//driver.findElement(By.id("password")).sendKeys("test12345");
//driver.findElement(By.name("proceed")).click();

//X-path
/*driver.findElement(By.xpath("//*[@type='text']")).sendKeys("anees");
driver.findElement(By.xpath("//input[contains(@name,'pass')]")).sendKeys("test1234");
driver.findElement(By.xpath("//input[@title='Sign in']")).click();*/

//css
//driver.findElement(By.cssSelector("input[type='text']")).sendKeys("anees");
//driver.findElement(By.cssSelector("input[type*='pass']")).sendKeys("test1234");
//driver.findElement(By.cssSelector("#password")).sendKeys("test1234");
//driver.findElement(By.cssSelector("input#password")).sendKeys("test1234");
//driver.findElement(By.cssSelector("input.signinbtn")).click();

// How to validate in console


//xpath - $x("xpath")
//css - $("css")

//Chropath extension for Chrome - install


driver.findElement(By.xpath("//input[@id='login1']")).sendKeys("anees");
driver.findElement(By.xpath("/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/div[1]/
div[2]/div[2]/div[2]/div[1]/input[1]")).sendKeys("testin123");
driver.findElement(By.cssSelector("input[value='Sign in']")).click();

}
2

Multiple Logins:

package Automation;

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

public class MultipleLogins {


static WebDriver driver;
public void login(String username, String password) {
driver.findElement(By.id("login1")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.name("proceed")).click();

String expectedvalue = "Wrong username and password combination.";


String actualvalue = driver.findElement(By.id("div_login_error")).getText();
System.out.println(actualvalue);
if (actualvalue.equals(expectedvalue))
{
System.out.println("Pass");
}
else {
System.out.println("fail");
}
driver.findElement(By.id("login1")).clear();
}

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\
BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://mail.rediff.com/cgi-bin/login.cgi");

MultipleLogins obj = new MultipleLogins();


obj.login("anees", "test1234");
obj.login("padma", "dgasfgsd");
obj.login("moosa", "shsrtyhrt");
obj.login("jaffar", "je5herht");
obj.login("tejaswi", "argefg");
obj.login("shakeer", "dfbsghbdrgb");

}
3

}
Static Dropdown
Inbox

package Automation;

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

public class Dropdown {

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\
SeleniumTraining\\BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://book.spicejet.com/");
driver.manage().window().maximize();

//script to select the currency dropdown


Select currdropdown = new
Select(driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputS
earchView_DropDownListCurrency")));
String x = currdropdown.getFirstSelectedOption().getText();
System.out.println(x);
//currdropdown.selectByIndex(7);
currdropdown.selectByValue("USD");
String y = currdropdown.getFirstSelectedOption().getText();
System.out.println(y);

currdropdown.selectByVisibleText("GBP");
String z = currdropdown.getFirstSelectedOption().getText();
System.out.println(z);

Xpath and Css

Xpath
tagName[@attribute='value']
//*[@attribute=’value’]
//tagName[contains(@attribute,'value')]
4

Css-
tagName[attribute='value']
tagName#id
#id
tagName.classname
tagName[attribute*='value']

Absolute XPath
/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/div[1]/div[2]/div[2]/div[2]/div[1]/
input[1]

Static Destination dropdown and Dynamic dropdow


DestinationFromTo :

package Automation;

import javax.swing.plaf.basic.BasicTableHeaderUI;

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;

public class DestinationFromTo {


static WebDriver driver;
public void Places(String Origin, String Destination)
{
driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
eworiginStation1_CTXT")).click();
driver.findElement(By.xpath("//a[@value='"+Origin+"']")).click();
driver.findElement(By.xpath("//a[@value='"+Destination+"']")).click()

HandlingCheckBox and calender


package Automation;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
5

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

public class HandlingCheckBox {

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\
SeleniumTraining\\BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://book.spicejet.com");
driver.manage().window().maximize();

String checkboxdiscount = "ladies";


//Script to select a option
//int countcheckbox =
driver.findElements(By.xpath("//input[@type='checkbox']")).size();
//System.out.println(countcheckbox);

//script to select a option


/*System.out.println(driver.findElement(By.id("ControlGroupSearchView_AvailabilityS
earchInputSearchView_Student")).isSelected());
driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_Student")).click();
System.out.println(driver.findElement(By.id("ControlGroupSearchView_AvailabilitySe
archInputSearchView_Student")).isSelected());
*/

//Script to read the text of all the checkbox


List<WebElement> discounts =
driver.findElements(By.xpath("//div[@id='divdiscountcheckbox']/div/div/p"));
for (WebElement singleoption :discounts)
{
//System.out.println(singleoption.getText());

if (singleoption.getText().equals(checkboxdiscount))
{
switch (singleoption.getText())
{

case "Family & Friends":


driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_FamilyAndFriends")).click();
break;

case "Sr. Citizen":


driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_SeniorCitizen")).click();
break;
6

case "Armed Forces":


driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_Defense")).click();
break;

case "LTC Fare":


driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_LTCFare")).click();
break;

case "Govt. Employee":


driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_GovtEmp")).click();
break;

case "Student":
driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_Student")).click();
break;

case "Unaccompanied Minor":


driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_UNMR")).click();
break;

default:
System.out.println("no discount group available");
break;

}
break;
}

---------------------

package Automation;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
7

import org.openqa.selenium.chrome.ChromeDriver;

public class Calendar {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\


SeleniumTraining\\BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://book.spicejet.com");
driver.manage().window().maximize();

List<WebElement> traveloptions = driver.findElements(By.id("travelOptions"));

for (WebElement option:traveloptions)


{
System.out.println(option.getText());
}

//script to select roundtrip


//driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearch
View_OneWay")).click();
//driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearch
View_RoundTrip")).click();
driver.findElement(By.id("custom_date_picker_id_1")).click();
String Firstheader = driver.findElement(By.xpath("//div[contains(@class,'ui-
datepicker-group-first')]/div/div")).getText();
System.out.println(Firstheader);
String Secondheader = driver.findElement(By.xpath("//div[contains(@class,'ui-
datepicker-group-last')]/div/div")).getText();
System.out.println(Secondheader);

if (Firstheader.equals("October 2022"))
{
driver.findElement(By.xpath("//td[contains(@class,'ui-datepicker-current-day
')]")).click();
}
}

Calender - to verify if Returndate field is enabled or disabled


package Automation;

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;
8

public class Calendar {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\


BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://book.spicejet.com");
driver.manage().window().maximize();

List<WebElement> traveloptions = driver.findElements(By.id("travelOptions"));

for (WebElement option:traveloptions)


{
System.out.println(option.getText());
}

/*
First we need to check If oneway is selected then only Departdate should be enabled.If
Round trip is selected then both the
Depart date and Return date should be enabled
To Identify Enable and Disable element
In general, if the element is disabled, upon click on element nothing should happen.
In latest technology though the UI field looks like disabled, it is not actually disabled. Still we
can click on this to open.
For this type of scenarios, is enabled method will not work. We need to get the Attribute
value of the element which is making
it look like disabled and verify it.
*/

//script to select roundtrip


driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_Ro
undTrip")).click();
if
(driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_On
eWay")).isSelected()==true)
{
String returnDatafielddisplay =
driver.findElement(By.id("marketDate_2")).getAttribute("style");
System.out.println(returnDatafielddisplay);
if (returnDatafielddisplay.contains("0.5"))
{
System.out.println("ReturnDate field is disabled");
}
else
{
System.out.println("ReturnDate field is enabled");
}

}
9

else
if(driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_R
oundTrip")).isSelected()==true)
{
String returnDatafielddisplay =
driver.findElement(By.id("marketDate_2")).getAttribute("style");
System.out.println(returnDatafielddisplay);
if (returnDatafielddisplay.contains("1"))
{
System.out.println("ReturnDate field is enabled");
}
else
{
System.out.println("ReturnDate field is disabled");
}
}
}

}
Calender - selecting specific date
package Automation;

import java.util.List;

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;

public class DoubleCalender {

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\
SeleniumTraining\\BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://book.spicejet.com");
driver.manage().window().maximize();

//script to click on departdate


//driver.findElement(By.id("custom_date_picker_id_1")).click();
String reqday="12";
String reqmonth = "August 2023";

WebElement element = driver.findElement(By.id("custom_date_picker_id_1"));


JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

for (int headers=1;headers<=9;headers++)


10

{
String Fisrstheader=driver.findElement(By.xpath("//div[contains(@class,'ui-
datepicker-group-first')]/div/div")).getText();
System.out.println(Fisrstheader);

String Secondheader=driver.findElement(By.xpath("//div[contains(@class,'ui-
datepicker-group-last')]/div/div")).getText();
System.out.println(Secondheader);

if (Fisrstheader.equals(reqmonth))

{
List<WebElement> alldays =
driver.findElements(By.xpath("//div[contains(@class,'ui-datepicker-group-first')]
//a[contains(@class,'ui-state-default')]"));
System.out.println(alldays.size());

for (int i=0; i<=alldays.size();i++)


{
System.out.println(alldays.get(i).getText());
if(alldays.get(i).getText().equals(reqday))
{
alldays.get(i).click();
break;
}

else if (Secondheader.equals(reqmonth))

{
List<WebElement> alldays =
driver.findElements(By.xpath("//div[contains(@class,'ui-datepicker-group-last')]
//a[contains(@class,'ui-state-default')]"));
System.out.println(alldays.size());

for (int i=0; i<=alldays.size();i++)


{
System.out.println(alldays.get(i).getText());
if(alldays.get(i).getText().equals(reqday))
{
alldays.get(i).click();
break;
}

}
break;
}
11

else
{
driver.findElement(By.xpath("//span[contains(@class,'ui-icon-circle-triangle-
e')]")).click();
}

}
}

}
mousehover actions
package Automation;

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

public class mouseHover {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\


BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://www.amazon.in");
driver.manage().window().maximize();

Actions mouse = new Actions(driver);


//mouse.moveToElement(driver.findElement(By.id("nav-link-accountList-nav-line-
1"))).perform();
//driver.findElement(By.xpath("//span[text()='Your Prime Video']")).click();
//System.out.println(driver.getCurrentUrl());

//Script to Right click


//mouse.moveToElement(driver.findElement(By.xpath("//span[text()='Your Prime
Video']"))).contextClick().perform();

//Script to enter capital letters


//mouse.moveToElement(driver.findElement(By.id("twotabsearchtextbox"))).click().keyDo
wn(Keys.SHIFT).sendKeys("television").perform();

//script to double click


mouse.moveToElement(driver.findElement(By.id("twotabsearchtextbox"))).click().keyDow
n(Keys.SHIFT).sendKeys("electronics").doubleClick().perform();
12

}
ALERT
package Automation;

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

public class Alerts {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\


BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.automationtesting.in/Alerts.html");
driver.manage().window().maximize();

//script to handle alert with ok button


/*driver.findElement(By.xpath("//button[contains(@class,'btn-danger')]")).click();
String alerttext = driver.switchTo().alert().getText();
System.out.println(alerttext);
driver.switchTo().alert().accept();*/

//script to dismiss alert


driver.findElement(By.xpath("//ul[contains(@class,'nav-tabs')]/li[2]")).click();
driver.findElement(By.cssSelector("button[onclick='confirmbox()']")).click();
String Alerttext= driver.switchTo().alert().getText();
System.out.println(Alerttext);
driver.switchTo().alert().dismiss();
String message=driver.findElement(By.id("demo")).getText();
System.out.println(message);

//script to enter text and accept

}
package Automation;

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

public class Alerts {


13

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\


BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.automationtesting.in/Alerts.html");
driver.manage().window().maximize();

//script to handle alert with ok button


/*driver.findElement(By.xpath("//button[contains(@class,'btn-danger')]")).click();
String alerttext = driver.switchTo().alert().getText();
System.out.println(alerttext);
driver.switchTo().alert().accept();*/

//script to dismiss alert


/*driver.findElement(By.xpath("//ul[contains(@class,'nav-tabs')]/li[2]")).click();
driver.findElement(By.cssSelector("button[onclick='confirmbox()']")).click();
String Alerttext= driver.switchTo().alert().getText();
System.out.println(Alerttext);
driver.switchTo().alert().dismiss();
String message=driver.findElement(By.id("demo")).getText();
System.out.println(message);*/

//script to enter text and accept


driver.findElement(By.xpath("//a[text()='Alert with Textbox ']")).click();
driver.findElement(By.xpath("//button[@onclick='promptbox()']")).click();
String message = driver.switchTo().alert().getText();
System.out.println(message);
driver.switchTo().alert().sendKeys("Testing");
driver.switchTo().alert().accept();

String typemesage = driver.findElement(By.id("demo1")).getText();


System.out.println(typemesage);
if (typemesage.contains("Testing"))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}
}

}
Drag and Drop
package Automation;

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

public class Alerts {


14

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\


BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.automationtesting.in/Alerts.html");
driver.manage().window().maximize();

//script to handle alert with ok button


/*driver.findElement(By.xpath("//button[contains(@class,'btn-danger')]")).click();
String alerttext = driver.switchTo().alert().getText();
System.out.println(alerttext);
driver.switchTo().alert().accept();*/

//script to dismiss alert


driver.findElement(By.xpath("//ul[contains(@class,'nav-tabs')]/li[2]")).click();
driver.findElement(By.cssSelector("button[onclick='confirmbox()']")).click();
String Alerttext= driver.switchTo().alert().getText();
System.out.println(Alerttext);
driver.switchTo().alert().dismiss();
String message=driver.findElement(By.id("demo")).getText();
System.out.println(message);

//script to enter text and accept

SCREEN SHOT
package Automation;

import java.io.File;
import java.io.IOException;

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

import com.google.common.io.Files;
15

public class Screenshot {

public static void main(String[] args) throws IOException {

System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\


BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://www.amazon.in");
driver.manage().window().maximize();

Actions mouse = new Actions(driver);

//script to double click


mouse.moveToElement(driver.findElement(By.id("twotabsearchtextbox"))).click().keyDown(Keys.SH
IFT).sendKeys("mobile").doubleClick().perform();
// File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
Files.copy(((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE), new File("E:\\Testing
Session\\SeleniumTraining\\testcase1.png"));

Synchronization:
Synchronization is a process to make both script and the Application under test into sink
There are 4 types of synchronization methods
1. ImplicitWait

2. ExplicitWait

3. Thread.Sleep

4. Fluent wait

Implicit wait is declared globally, if we set 5secs, then it will wait by default 5secs before
throughing error message, it is applicable for all the elements
16

driver.manage().timeouts().implicitlyWait(5,TimeUnit.seconds)

Explicit Wait is declared at specific element.

Give Bank transaction example – fund transfer, online payment, mini statement, update
personal info, Bank statement for 1 year

WebDriverWait wait=new WebDriverWait(driver, secs)


Wait.until(ExpectedConditions.visibilityofelementlocated(by.id(“ “)));

Fluent Wait:
Fluent wait is also a type of explicit wait
Fluent wait finds the web element repeatedly at regular intervals of time until the timeout
or till the element is found
Synchronisation example:

Implicit wait: Implicit wait time is applied on all elements. No need to specify any conditions for
wait.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

Explicit wait: Explicit wait is applied on only one element which is given by us. We need to
specify a condition for that web element before proceeding further in the code.

WebDriverWait wait = new WebDriverWait(driver, 20);


wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//
button[@id='hidden']")));

Fluent wait: Fluent wait is a wait in Selenium in which we can give maximum amount
of time to wait for specific condition with a polling time to check the web element in
regular intervals. We can also configure the wait to ignore any exception during polling period before
throwing “ElementNotVisibleException”.

FluentWait wait = new FluentWait(driver);


.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)

Excericise:

package Automation;

import java.util.concurrent.TimeUnit;

import javax.xml.datatype.Duration;

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

import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;

public class Synchronization {

public static void main(String[] args) throws InterruptedException {


System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\
SeleniumTraining\\BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://chercher.tech/practice/explicit-wait-sample-selenium-webdriver");
driver.manage().window().maximize();

//Implicitwait
//driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
/*driver.findElement(By.id("alert")).click();
String alertmsg=driver.switchTo().alert().getText();
System.out.println(alertmsg);*/

//Explicitwait
driver.findElement(By.id("display-other-button")).click();
boolean btn = driver.findElement(By.id("hidden")).isDisplayed();
System.out.println(btn);

WebDriverWait wait = new WebDriverWait(driver, 30);


wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("hidden")));
boolean btn1 = driver.findElement(By.id("hidden")).isDisplayed();
System.out.println(btn1);

//Fluent Wait
FluentWait Wait1 = new FluentWait(driver);
Wait1.withTimeout(50, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS);

Window Handle:
If in our project you need to run your script on more than one window, pon
click on some button or link a url might be opened as a tab or new window. In
this case you need to implement window Handles concept. Firstly, we need to
inform driver that you need to getwindowhandles and set those into a string
value. As there are multiple windows we need to iterate among them so we
need to add a statement for iterator. Initially the focus will be outside. We
need to make focus on parent and then child using the statement it.next() and
then you can inform driver to switch its focus to parent or child.

Exercise:
18

package Automation;

import java.util.Iterator;
import java.util.Set;

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

public class windowsHandling {

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\
SeleniumTraining\\BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.automationtesting.in/Windows.html");
driver.manage().window().maximize();

//Script to perform action on new tab


/*
driver.findElement(By.xpath("//button[contains(@class,'btn-
info')]")).click();

Set<String> window = driver.getWindowHandles();


Iterator<String> it = window.iterator();
String parent = it.next();
System.out.println(parent);
String child = it.next();
System.out.println(child);

driver.switchTo().window(child);
String message =
driver.findElement(By.xpath("//div[@class='text-center']/h1")).getText();
System.out.println(message);

driver.switchTo().window(parent);
driver.findElement(By.xpath("//ul[contains(@class,'nav-stacked')]/
li[2]")).click();
//driver.close();
driver.quit();
*/

//Script to perform action on new window


driver.findElement(By.xpath("//ul[contains(@class,'nav-stacked')]/
li[2]")).click();
driver.findElement(By.xpath("//button[contains(@onclick,'newwindow()')]")).cl
ick();

Set<String> window = driver.getWindowHandles();


Iterator<String> it = window.iterator();
String parent = it.next();
System.out.println(parent);
String child = it.next();
System.out.println(child);

driver.switchTo().window(child);
String message1 =
driver.findElement(By.xpath("//div[@class='text-center']/h1")).getText();
19

System.out.println(message1);

Frame: Frames are a component which are hosted in webpage

iFrame in Selenium Webdriver is a web page or an inline frame which is embedded in another web page. The
iframe is often used to add content from other sources like an advertisement into a web page. The iframe is
defined with the <iframe> tag

We can identify the frames in Selenium –

 Right click on the element, If you find the option like ‘This Frame’ or ‘View Frame source’ or ‘Reload
frame’ then it is an iframe

 Right click on the page and click ‘View Page Source’ and Search with the ‘iframe’, if you can find any
tag name with the ‘iframe’ then it is meaning to say the page consisting an iframe.

We can switch over the elements and handle frames in Selenium using 3 ways.

 By Index

 By Name or Id

 By Web Element

Switch to the frame by index: - When there are multiple frames in page, we can switch to
frame in Selenium by using index.

driver.switchTo().frame(0); //int
driver.switchTo().frame(1);

Switch to the frame by Name or ID: - Name and ID are attributes for handling frames in Selenium through
which we can switch to the iframe.

driver.switchTo().frame(“iframe1”); // String
driver.switchTo().frame(“id”);

Switch to the frame by Web Element: - We can even switch to the iframe using web element .

driver.switchTo().frame(WebElement);

Switch back to the Main Frame - we have to come out of the iframe.

To move back to the parent frame, we can either use switchTo().parentFrame() or if you want to get back to the
main frame, you can use switchTo().defaultContent();

driver.switchTo().parentFrame();
driver.switchTo().defaultContent();

To find the total number of iframes present inside the page using the tagname ‘iframe’ –
int size = driver.findElements(By.tagName("iframe")).size();

Exercise:

package Automation;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
20

import org.openqa.selenium.chrome.ChromeDriver;

public class iFrames {

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "E:\\Testing Session\\SeleniumTraining\\
BrowserDrivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.automationtesting.in/Frames.html");
driver.manage().window().maximize();

//driver.switchTo().frame(0); //frame using index

//driver.switchTo().frame("singleframe"); // by frame name

driver.switchTo().frame(driver.findElement(By.id("singleframe"))); //frames with webelement

driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Testing");

driver.switchTo().defaultContent();
driver.findElement(By.xpath("//ul[contains(@class,'nav-tabs')]/li[2]")).click();

Framework:

Assertion:
https://mvnrepository.com/artifact/org.testng/testng/6.7
For Assertions, we have a TestNG frame work which we use. Download the TestNG jar
Access this URl à https://jar-download.com/artifacts/org.testng/testng
Click on Download testng.jar and unzip the downloaded file and attach the jar
files to build path

Eg:
Assert.assertTrue(true);
Assert.assertEquals(Actualtextmessage, ExpectedMessage);
21

Install and configure TestNG in Eclipse:


Goto Help in Eclipse à Select Eclipse Market place à type Testng and
searchà installà restart the eclipse

To verify the installation is success:


Goto Eclipse after restart à click on window à click on preference à type
testng

Project name: Banking


Loan Department
Module1: Personal loan
Module2: home loan
Module3: Car loan

Personal loan: flexi loan, fixed loan


Home loan: smart loan, mortage loan
Carloan: carlease, carBuy

Create 6 class files with each class having 3 testcases


@Test
Execute all the 6 class files individually
Now convert to TestNG xml file to execute all together
Run testing file
Verify the report generated

Creation of TestNG xml file


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="LoansDepartment">
<test name="Homeloan">
<classes>
<class name="TestAutomation.mortageloan"/>
<class name="TestAutomation.fixedloan"/>
</classes>
</test>

<test name="Personalloan">
<classes>
<class name="TestAutomation.flexiloan"/>
<class name="TestAutomation.smartloan"/>
</classes>
</test>

<test name="Carloan">
<classes>
<class name="TestAutomation.carBuyloan"/>
<class name="TestAutomation.carleaseloan"/>
</classes>
</test>
</suite>
22

----------------------------

How to exclude few test cases without executing from a class file
Now, assume there are 3 test cases in a class, if you want to run only 1 test case Then you
can exclude other 2 test cases
<?xml version="1.0" encoding="UTF-8"?>
<suite name="LoansDepartment">
<test name="Homeloan">
<classes>
<class name="TestAutomation.mortageloan">
<methods>
<exclude name="mortageloanloginwithWEB"/>
<exclude name="mortageloanloginwithAPP"/>
</methods>
</class>
</classes>
</test>
</suite>

How to execute only specific test cases without executing all test cases from a class file
Now, assume there are 3 test cases in a class, if you want to run only 1 test case Then you
can add include method

<?xml version="1.0" encoding="UTF-8"?>


<suite name="LoansDepartment">
<test name="Homeloan">
<classes>
<class name="TestAutomation.mortageloan">
<methods>
<include name="mortageloanloginwithBranch"/>
</methods>
</class>
</classes>
</test>
</suite>

-----------------------

Regular Expression:
Now in one Class file if there are 6 test cases related to Web and 2 test cases
related to APP and Branch. If the user want to run only the test cases related to
Web(6 test cases), in this case instad of excluding the oher two test cases, we
can include with regular expression fixedloanloginWeb.*

fixedloanloginweballvalid
fixedloanloginwebvaliduser
fixedloanloginwebinvaliduser
23

fixedloanloginwebinvalidpassword
fixedloanloginwebblank
fixedloanloginAPP
fixedloanloginBranch

<?xml version="1.0" encoding="UTF-8"?>


<suite name="LoansDepartment">
<test name="Homeloan">
<classes>
<class name="TestAutomation.fixedloan">
<methods>
<include name="fixedloanloginWeb.*"/>
</methods>
</class>
</classes>
</test>
</suite>

--------------------------

How to execute only sanity test cases or only regression test cases
To handle this type of test exection, TestNG framework has comeup with a concept called
“Grouping”
For this we need to add a system like
@Test (groups={“sanity”})
And need to update the TestNG.xml file as below
<?xml version="1.0" encoding="UTF-8"?>
<suite name="LoansDepartment">
<test name="Homeloan">
<groups>
<run>
<include name ="sanity"/>
</run>
</groups>
<classes>
<class name="TestAutomation.carBuyloan"/>
<class name="TestAutomation.carleaseloan"/>
<class name="TestAutomation.fixedloan"/>
<class name="TestAutomation.flexiloan"/>
<class name="TestAutomation.mortageloan"/>
<class name="TestAutomation.smartloan"/>
</classes>
</test>
</suite>

--------------------------

Depends On
24

Now assume a scenario where one test case output should be input from other test case it
means one test case is depended on other test cases to execute. To handle such type of
cases TestNG has a concept called “Depends on Methods”
@Test(dependsOnMethods = {"fixedloanloginwithWEBsplcharuser"})

Enable/Disable Test Case

Assume a scenario where you have 100 test cases in a suite and there is a defect which is
causing 2 test cases to fail. Everyone when you execute the automation suite the both test
cases are failing which s expected due to the open defect. To handle such type of cases
TestNG has a flag/switch called “enabled”
@Test(enabled=false)

Priority Setting:

@Test(priority = 1)
public void CarBuyLoanLoanWEB()
{
System.out.println("CarBuyLoan from WEB");
}

@Test(priority = 2)
public void CarBuyLoanAPP()
{
System.out.println("CarBuyLoan from APP");
Assert.assertTrue(true);
}

@Test(priority = 0)
public void CarBuyLoanBranch()
{
System.out.println("CarBuyLoan from Branch");
}

-----

TestNG Annotation

@BeforeSuite - The @BeforeSuite annotated method will run before the execution of
all the test methods in the suite.
@AfterSuite - The @AfterSuite annotated method will run after the execution of all
the test methods in the suite.
@BeforeTest - The @BeforeTest annotated method will be executed before the
execution of all the test methods of available classes belonging to that folder.
25

@AfterTest - The @AfterTest annotated method will be executed after the execution
of all the test methods of available classes belonging to that folder.
@BeforeClass - The @BeforeClass annotated method will be executed before the
first method of the current class is invoked.
@AfterClass - The @AfterClass annotated method will be invoked after the
execution of all the test methods of the current class.
@BeforeMethod - The @BeforeMethod annotated method will be executed before
each test method will run.
@AfterMethod - The @AfterMethod annotated method will run after the execution of
each test method.
-----------------------------------------------------------------

package testingFramework;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

public class Testannotations {

@BeforeSuite
public void beforesuite()
{
System.out.println("Before Suite");
}

@AfterSuite
public void aftersuite()
{
System.out.println("after Suite");
}

@BeforeTest
public void BeforeTest()
{
System.out.println("Before Test");
}

@AfterTest
public void AfterTest()
{
System.out.println("After Test");
}
26

@BeforeMethod
public void BeforeMethod()
{
System.out.println("Before Method");
}

@AfterMethod
public void AfterMethod()
{
System.out.println("After Method");
}

@BeforeClass
public void BeforeClass()
{
System.out.println("Before Class");
}

@AfterClass
public void AfterClass()
{
System.out.println("After class");
}

Property file - To Read data from external property file


Data Properties file :

#savingfile
#Sat Oct 22 20:27:27 GMT-12:00 2022
password=test1234
browser=chrome
training=Selenium
place=brussels
url=www.google.com
username=anees

Exercise:

package testingFramework;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
27

public class readData {

public static void main(String[] args) throws IOException {


Properties prop = new Properties();
FileInputStream fis = new FileInputStream("E:\\Testing Session\\SeleniumTraining\\
Fourth Batch Training\\SeleniumTraining\\data.properties");

prop.load(fis);

//Script to read data from property file


System.out.println(prop.getProperty("username"));
System.out.println(prop.getProperty("browser"));
System.out.println(prop.getProperty("password"));

//Script to write data to property file


prop.setProperty("training", "Selenium");
prop.setProperty("place", "brussels");
System.out.println(prop.getProperty("training"));

FileOutputStream fos = new FileOutputStream("E:\\\\Testing Session\\\\


SeleniumTraining\\\\Fourth Batch Training\\\\SeleniumTraining\\\\data.properties");
prop.store(fos, "savingfile");

GIT :
https://git-scm.com/downloads - to downlaod and install

https://github.com/ - to create an account

GitHub is a website and cloud-based service that helps developers/testerd store and
manage their code. As well as track and control changes to their code.

https://github.com/testadmin155/shinningteam.git

Commands:

1. GIT init :
The git init command is the first command that you will run on Git.
The git init command is used to create a new blank repository.
It is used to make an existing project as a Git project.

2. git remote add origin <url>(https://github.com/testautomation/<repositoryname>) - this


command is used to create a connection between GITHUB server and the local project
28

3. git status - this command is used to check what are files need to be commited

4. git add . - this will add all the files which all need to be commited

5. git status - everything should be in green

6. git commit -m "loginpage code"(comment)

7. git push origin master


If you get set permission error

8. then need to add SSH key of teh user system in the GITHUB Repository to get the
access.

9. git clone <url>(https://github.com/testautomation/<repositoryname>)


this commands helps to take the first version of teh test
Firsttime when we are pulling any Repository from any github server we need to run this
clone command we. it is nothing but making local repository

10. git pull origin master

GIT :
GitHub is a website and cloud-based service that helps developers/testerd store and manage
their code. As well as track and control changes to their code.

1. downlaod and install - https://git-scm.com/downloads


2. Goto Environmant variable and set the below two Path
C:\Program Files\Git\cmd
C:\Program Files\Git\bin\

3. create an account - https://github.com/


4. login to the account
5. click on + and click on create a NEw Repository
6. enter some unique name for teh repository
7. select public and click on Create repository
8. Copy the Repository Path(URL) - https://github.com/testadmin155/shinningteam.git

How to Push the code from local system to a given Repository:

Commands:

1. GIT init :
The git init command is the first command that you will run on Git.
The git init command is used to create a new blank repository.
It is used to make an existing project as a Git project.

2. git remote add origin <url>(https://github.com/testautomation/<repositoryname>) - this


command is used to create a connection between GITHUB server and the local project

3. git status - this command is used to check what are files need to be commited
29

4. git add . - this will add all the files which all need to be commited

5. git status - everything should be in green

6. git commit -m "loginpage code"(comment)

7. git push origin master

If you get set permission error

8. then need to add SSH key of teh user system in the GITHUB Repository to get the access.

How to Pull the code given Repository to local system first time:

1. git clone <url>(https://github.com/testautomation/<repositoryname>)


this commands helps to take the first version of teh test
First time when we are pulling any Repository from any github server we need to run this
clone command we. it is nothing but making local repository

How to pull the code from Next time after clone.


2. git pull origin master

Maven:
Maven is a software Management tool. It will take care few things to manage project.
it acts as a build Management tool for java framework
Using Maven commands we can execute the script from Jenkins

Installation of Maven

Goto Google : Search for MAven download --> click on first link and download the zip
file for widows.
Download Maven - https://maven.apache.org/download.cgi
download file - apache-maven-3.8.6-bin.zip

Unzip the file and set the environemnt variables

goto Environment variables and Set the Path and set the MAVEN_HOME
open Path and add : E:\Testing Session\SeleniumTraining\Maveninstaller\apache-
maven-3.8.6-bin\apache-maven-3.8.6\bin
MAVEN_HOME : E:\Testing Session\SeleniumTraining\Maveninstaller\apache-
maven-3.8.6-bin\apache-maven-3.8.6

command to find the version of maven : mvn --version


30

From Eclipse --> create a Maven project


file --> New --> Project --> Maven project --> select the groupid "org.apache.maven:
maven-archetype-quickstart"
Enter the groupid as project name
Artifact id as feature name

click on next and finish

ALl the test cases are maintained at src/test/java folder


All the utility files and Page Object model fiels are maintained at src/main/java folder

Pom.xml file is teh heart of Maven

All the requried dependencies are save in pom.xml file

Create multiple clases and tests under each class

Create a TestNG.xml file

Add Selenium and TestNG dependencies


https://mvnrepository.com/ - to take selenium dependencies and TestNG
dependencies
selenium 3.141.59
TestNG 6.8.8
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java

Add the maven surefire plugins to POM.xml to execute the testng.xml file using
command line -
https://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html

Goto Project folder(where pom.xml file ispresent and open CMD


run the command to execute all teh class file and all teh test cases from testng.xml -
mvn test
run the command to execute specific test class - mvn -Dtest=loginTest test

Maven Profiling:
We can create the groups in TestNg and call the specific profiles from Pom.xml
create multiple TestNG files(Sanity, Regression, Full) and create its corresponding
profiles in POM.xml

Run the command


mvn test -PRegression
mvn test -PSanity
mvn test -PFull

POX.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
31

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/
xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>MavenProject</groupId>
<artifactId>FirstScript</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>FirstScript</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<profiles>
<profile>
<id>Sanity</id>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testngSanity.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>

<profile>
<id>Regression</id>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testngRegression.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
32

</plugins>
</pluginManagement>
</build>
</profile>

<profile>
<id>Full</id>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testngFull.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>

<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>

--------------------------------------------------------------------------
33

TestNGSanity.xml:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<groups>
<run>
<include name ="Sanity"/>
</run>
</groups>

<test thread-count="5" name="Test">


<classes>
<class name="MavenProject.FirstScript.PersonalLoan"/>
<class name="MavenProject.FirstScript.CarLoan"/>
<class name="MavenProject.FirstScript.Homeloan"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

TestNGRegression:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<groups>
<run>
<exclude name ="Sanity"/>
</run>
</groups>

<test thread-count="5" name="Test">


<classes>
<class name="MavenProject.FirstScript.PersonalLoan"/>
<class name="MavenProject.FirstScript.CarLoan"/>
<class name="MavenProject.FirstScript.Homeloan"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

TestNGFull.xml:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="MavenProject.FirstScript.PersonalLoan"/>
34

<class name="MavenProject.FirstScript.CarLoan"/>
<class name="MavenProject.FirstScript.Homeloan"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Tests:
CarLoan :

package MavenProject.FirstScript;

import org.testng.annotations.Test;

public class CarLoan {

@Test(groups= {"Sanity"})
public void logintoBranchforCarLoan()
{
System.out.println("logintoBranchforCarLoan");
}

@Test
public void logintoAPPforCarLoan()
{
System.out.println("logintoAPPforCarLoan");
}

Homeloan :

package MavenProject.FirstScript;

import org.testng.annotations.Test;

public class Homeloan {

@Test(groups= {"Sanity"})
public void logintoBranchforHomeLoan()
{
System.out.println("logintoBranchforHomeLoan");
}

@Test
public void logintoAPPforHomeLoan()
{
System.out.println("logintoAPPforHomeLoan");
35

PersonalLoan :

package MavenProject.FirstScript;

import org.testng.annotations.Test;

public class PersonalLoan {

@Test(groups= {"Sanity"})
public void logintoBranchforPersonalLoan()
{
System.out.println("logintoBranchforCPersonalLoan");
}

@Test
public void logintoAPPforPersonalLoan()
{
System.out.println("logintoAPPforPersonalLoan");
}

You might also like