Selenium Notes
Selenium Notes
Selenium supports 14 diff coding languages ( java, python, js,C#, php, pearl,…..)
Platform independent
Selenium is a community in which we will learn selenium webdriver..
Using selenium we can automate only web applications. (only functional testing)
For performance testing we need to integrate it with the LOADRUNNER & J
meter.
Client server app -->Selendroid , APPIUM.
Stand alone app → Winium
INTRODUCTION OF SELENIUM
Selenium is a free and open source, web application automation tool ,or
functional testing web application automation tool.
=============================================================
=============================================================
Architecture of SELENIUM
Selenium supports 14 diff. Coding languages such as java, python, ruby etc...
These are called Language binding or Client binding.
This client binding communicates with selenium server standalone. Then
performs action of the browser with the help of driver executables, in order to
perform action it uses JSON wire protocol
(javascript object notation).
Selenium server internally contains selenium java client binding also.hence by
installing selenium we use only jar file and driver executable files.
1. Download selenium server jar file and browser specific driver executable
file in the download page of selenium website .
2. Extract the driver executable file (unzip the file)
3. in eclipse create a new java project and create two new folders such as jar
and driver inside the java project.
4. Copy and paste the driver executable file into the driver folder.
5. Similarly copy and paste selenium jar file into jar folder.
6. Add jar file to build path.so that we can use import statement to import
required classes of selenium.
Note: do not add driver.exe file to the build path, because eclipse will not
allow us to add exe file to the build path.
7. To specify the path either we add it manually to the environment variable or
we should add it programmatically using system.setproperty.
8. While specifying the path we use relative path by specifying dot . operator at
the beginning which represents the current java project.
9. We should set the path before opening the browser or else we get an illegal
state exception error.
10. For easy maintenance we set the path of all drive executables in the static
block as shown below
package qsp;
import org.openqa.selenium.chrome.ChromeDriver;
Note: Eclipse will display methods of object class also when we press . dot after
any reference variable. To hide it go to the window tab click on preferences >>
java >> appearances >> type filters >> click on add >> type: java.lang.Object >>
click on OK >> apply and close.
Methods of WebDriver
close()
get()
getCurrentUrl()
getPageSource()
getTitle()
getWindowHandle()
getWindowHandles()
manage()
navigate()
quit()
switchTo()
Methods of JavaScriptExecutor
executeScript()
executeAsyncScript()
Methods of TakeScreenshots
getScreenshotAs()
Methods of WebElement
clear()
click()
getAttribute()
getCssValue()
getLocation()
getRect()
getSize()
getTagName()
getText()
isDisplayed()
isEnabled()
isSelected()
sendKeys()
submit()
WebElement
-Anything present on the web page is called as webelement such as button, text
box, link, etc.
-Webelements are created using HTML language(hypertext markup language).
-HTML element contains 3 things
1.Tag
2.Attribute
3.Text
Example. HTML code of a login button is <div id=”d1”>Login</div>
In the above HTML code div is the Tag, id is the Attribute name, d1 is the
attribute value, Login is the Text (visible text).
- In order to see the HTML code of the required element right click on that
element and select the option Inspect. If right clicking is disabled on the
page then press Ctr+shift+i or F12. It will display a developer toolbar.
- In order to inspect another element click on the inspect button and then
click on the required element.
Locators
Locators are used to find the element, in selenium there are 8 types of locators
and all of them are static methods present in By class.
By is an abstract class.
1.tagName()
2.id()
3.name()
4.className()
5.linkText()
6.partialLinkText()
7.cssSelector()
8.xpath()
<html>
<body>
<a id="d1" name="n1" class="c1" href="https://qspiders.com/">Qspiders</a><br>
<a id="d1" name="n1" class="c1" href="https://jspiders.com/">Jspiders</a>
</body>
</html>
Jspiders/ Qspiders
** we can use linkText() and partiaLinkText() only when the tag name is a **
Limitations of partialLInkText()
1.Element should be a link. Ex: <span>Inbox(7)</span>
2. Text should be partially changing. Ex: <span>25</span>
cssSelector()
-Css stands for Cascading style sheet.
-cssSelector is one of the locator in selenium.
- the syntax is :
Tag[attribute name = ‘attribute value’]
Example: a[id=’d1’]
a[name=’n1’]
a[class=’c1’]
a[href=’https://jspiders.com/’]
These all are called css expressions.
- We can check the css expression in the browser by using following steps:
1. Inspect any element.
2. Press Ctr+f .
3. Type the above expression.
4. 1 of 1 >> 1 matching element
5. 1 of 3 >> multiple matching elements
6. 0 of 0 >> no matching elements
System.setProperty("webdriver.chrome.driver","./driver/chromedriver.exe");
}
driver.findElement(By.cssSelector("a[href='https://jspiders.com/']")).click();
driver.navigate().back();
}
Note:
Limitation of cssSelector is we can’t use text or it doesn’t support text.
Note: if we make any syntax mistake while writing css expression or xpath, then
we get an InvalidSelectorException.
xpath()
-Path of the element in a HTML tree is called xpath. While writing xpath its starts
with .(dot) which represents the current web page or html document.
-Using .(dot) is not mandatory.
-To navigate from parent element to child element we use / (single forward
slash).
-xpath expression is .html/body/a (or) html/body/a
-selenium code for xpath is
driver.findElements(By.xpath(“/html/body/a”)).click
Xpath index
In xpath we can use an index which starts from 1, then if there is another
element under the same parent with the same tag then index becomes 2
and so on.
Html
|__ body
|
1 |__ div
1 |__ a link1
2 |__ a link2
|
2 |__div
1 |__ a link3
1 |__ img image
2 |__ a link4
Link 1: /html/body/div[1]/a[1]
Link 2: /html/body/div[1]/a[2]
Link 3: /html/body/div[2]/a[1]
Link 4: /html/body/div[2]/a[2]
Link 1 and link 2: /html/body/div/a
Link 3 and link 4: /html/body/div[2]/a
Link 1 and link 3: /html/body/div/a[1]
Link 2 and link 4: /html/body/div/a[2]
Link 1,2,3,4: /html/body/div/a
Image: /html/body/div[2]/img (or) /html/body/div/img
{here it will check in both div}
2. Relative xpath
Relative starts with //(double forward slash) which represents descendants
(child, grandchild, great grandchild….).
A.xpath by attribute
B. xpath by text function
C. xpath by contains function
D. traversing xpath
E. independent dependent xpath
F. xpath by group index
Link 1: //div[1]/a[1]
Link 2: //div[1]/a[2]
Link 3: //div[2]/a[1]
Link 4: //div[2]/a[2]
Link 1 and link 2: //div/a
Link 3 and link 4: //div[2]/a
Link 1 and link 3: //div/a[1] (or) //a[1]
Link 2 and link 4: //div/a[2] (or) //a[2]
Link 1,2,3,4: //div/a
Image: //div/img (or) //img (or) //div/img[1]
Q: How do you find all the links and all the images for any given web app or
web page?
//a | //img
Link1 and link 4 : //div[1]/a[1] | //div[2]/a[2]
Link 2 and link3 : //div[1]/a[2] | div[2]/a[1]
P Q
A B
C D
Html
|__body
|__a P
|__a Q
|__table
|__a A
|__a B
|__a C
|__a D
//tag[@AN =’AV’]
9.Unselected checkbox
>> //input[not(@checked) and @type=’checkbox’]
Ex2-
<td id=”headerContainer” class=”header”>Please identify yourself</td>
Xpath is: //td[text()=’Please identify yourself’]
Assignment
Write a script to login to actiTIME application.
Use SendKeys(‘admin’)
D. traversing xpath
Navigating from one element to another element is called traversing.
- There are 2 types of traversing
1. Forward traversing
2. Backward traversing
- Navigating from parent element to child element is called forward
traversing.
- Navigating from child element to parent element is called backward
traversing.
- Sample html code is
<table border =”1”>
<tr>
<td>java</td>
<td>100</td>
</tr>
<tr>
<td>selenium</td>
<td>300</td>
</tr>
</table>
java 100
selenium 300
Html
|__body
|__table
|__tbody
1 |__tr
1 |__td java
2 |__td 100
2 |__tr
1 |__td selenium
2 |__td 300
Xpath: //td[.=’selenium’]/../td[2]
Q: Write an xpath to identify the set by default link for manufacturing type
of work?
//td[@class='listtblcell billingTypeCell']/../td[5]/span
Q: Write an xpath to identify the price of libas kurtas present under the
women's section of myntra?
(//h3[.='Libas'])[1]/../div/span/span
Q: Write an xpath to identify the price of h&m jeans present under the kids
section of myntra?
(//h3[.='H&M'])[1]/../div/span/span
Html
|__body
1 |__div
1 |__a A
2 |__a B
2 |__div
1 |__ a C
2 |__ a D
When we use group index 1s it will execute the expression present inside the (),
in this example 1st it will execute //a and it will store matching elements i.e,
ABCD links into xpath array where index starts from 1.
Then it will identify the matching element based on the index which is specified
outside the ( ), in this example it matches with 1st link A.
selenium 100
selenium 300
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("manager");
driver.findElement(By.xpath("//div[text() ='Login ']")).click();
}
}
Q: Write a script to remove the text from the text box in OpenSourceBilling
app(email and password text box) ?
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
Assignment
Write a script to check whether the login button is working or not in
facebook.com
isEnabled()
}
}
Write a script to print the status of the checkbox present in actiTIME app ?
isSelected()
}
}
Q: Write a script to print the height and width of the login button of
facebook ?
Assignment
Write a script to check whether height and width of username and
password text box are equal or not for actiTIME ?
Write a script to print a text of submit button along with the tag name and
class attribute of OpenSourceBilling app ?
getTagName() , getText(), getAttribute(class)
Q: write a script to check whether username and password text box are
properly aligned or not?
Q: write a script to print the color of the forgotten password link present in
facebook.com?
getcssValue() is used to fetch the value of css like font, color, etc.
findElements()
………………….image………………...
Html code:
<html>
<body>
<a id="d1" name="n1" class="c1" href="https://qspiders.com/">Qspiders</a><br>
<a id="d1" name="n1" class="c1" href="https://jspiders.com/">Jspiders</a>
</body>
</html>
Note:
In order to take the input from the user use the below code-
Assignment:
Q:Write the above 2 programs using for each loop
Q:Automate the following scenario
1.open the browser.
2. Go to flipkart.com type iphone in the search text box find all the
auto suggestions.
3.print all the auto suggestions along with count(using for each loop).
4.click on the last auto suggestion.
findElement() findElements()
1.Return type of findElement is 1.Return type is list of WebElements.
WebElement.
2.if the locator is not matching it will 2. Here it returns an empty list.
throw a NoSuchElementException.
3. If the locators are matching with 3. It returns all the matching elements
multiple elements it will return the 1st
matching element.
4. Used to handle a single element. 4. Used to handle multiple elements.
Synchronization
Implicit wait()
-In selenium there are different ways to synchronize the sleep
-One of the frequently used options is Implicit wait.
The Syntax is -
driver.manage().timeouts().implicitlyWait( time, TimeUnit.SECONDS);
It takes 2 arguments
1.time duration(long)
2.timeUnit (microseconds, milliseconds, seconds. Minutes, hours, days etc)
The specified duration is used only by findElements and findElement statement
- means implicit wait will work only for findElements() and findElement().
Default value for implicit wait is zero second.
Flow diagram
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("manager");
driver.findElement(By.xpath("//div[text() ='Login ']")).click();
driver.findElement(By.className("logout")).click();
}
}
Explicit wait()
In order to handle the synchronization of any method, we can use explicit wait.
WebDriverWait itself is called an explicit wait, because we have to specify the
waiting condition explicitly.
Flow diagram
When the controls comes to wait.until statement it will check the specific
condition.
If the condition is true it will go to the next statement, if the condition is false it will
check for the time out.
If the time is over, it will throw TimeOutException, else it will wait for 500ms and it
will continue to check the condition.
Note: in the above flow diagram titleIs is the condition.
By using explicit wait we can handle the synchronization of any statement
but only one at a time.
Script:
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("manager");
driver.findElement(By.xpath("//div[text() ='Login ']")).click();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.titleContains("Enter"));
// wait.until(ExpectedConditions.titleIs("actiTIME - Enter
Time-Track"));
String title= driver.getTitle();
System.out.println(title);
driver.close();
}
}
Note:
ExpectedCondition is an interface and ExpectedConditions is a class.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("logoutLink")));
driver.findElement(By.id("logoutLink")).click();
driver.close();
}
}
CustomWait:
Handling the synchronization of the automation script by writing our own java
code is called as custom wait.
Example
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("manager");
driver.findElement(By.xpath("//div[text() ='Login ']")).click();
int i = 0;
while(i<1000)
{
try
{
driver.findElement(By.id("logoutLink")).click();
break;
}
catch(NoSuchElementException e)
{
i++ ;
}
}
//driver.close();
}
}
ImplicitWait ExplicitWait
1.We don’t specify the waiting 1.We should specify the waiting
condition explicitly. condition explicitly.
2. We can handle the sync of all the 2. We can handle the sync of any
findElement() and findElements(). method but only one at a time.
Q: write a script to check whether the login page is loaded within 15s or
not?
Q: Write a script to copy the text present in the email text box and paste it
into the password text box for OpenSourceBilling app.
driver.findElement(By.id("password")).sendKeys(Keys.CONTROL+"av");
}
}
- Whenever a listbox is created using select tag and content of the listbox is
created using Option tag.
- Then to handle this listbox we use the select class of selenium. It should
be imported from ‘org.openqa.selenium.support.ui‘ package.
- Select class has a parameterised constructor where it takes an argument
of type webelement (address of the listbox).
- In order to perform action on the listbox we can use anyone of the
following methods:
1. selectByIndex(int) >>>> takes int as an argument
2. selectByValue(String) >>>> takes String as an argument
3. selectByVisibleText(String)
4. deSelectByIndex(int)
5. deSelectByValue(String)
6. deSelectByVisibleText(String)
7. deSelectAll()
8. getFirstSelectedOption()
9. getAllSelectedOption()
10. isMultiple()
11. getOptions()
12. getWrappedElement()
Q: write a script to select the options present in the month listbox present
in facebook?
Assignment
Q: Write a script to select your DOB on facebook.com?
public class FacebookDob {
static {
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
Note:
-If the specific option is duplicate then it will select the 1st matching element, if
the specific option is not present then it will throw NoSuchElementException.
-if you try to use deSelect() on the single select listbox we get
UnsupportedOperationException.
-While creating the object of the select class if we specify the WebElement which
is not a listbox then we get UnexpectedTagNameException.
Q: Write a script to print the first selected element present in the SLV
listbox?
public class FirstSelectedOpt {
static {
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
Q: write a script to print all the options present in the MTR listbox?
Assignment:
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("iphone
12"+ Keys.ENTER);
List<WebElement> proName =
driver.findElements(By.xpath("//div[@class='_4rR01T']"));
List<WebElement> price =
driver.findElements(By.xpath("//div[@class='_30jeq3 _1_WHN1']"));
int count = proName.size();
System.out.println(count);
for(int i=0;i<count;i++) {
String text = proName.get(i).getText();
String text1 = price.get(i).getText();
System.out.println(text+ "--->"+ text1);
}
driver.close();
}
}
2. Write a script to search for wipro jobs in google.com and capture all
the URLs (after navigating to search page by clicking enter)
Inside for loop
allLInks = get(i).get(Attribute(href));
5. Write a script to print all the duplicate options present in the MTR
listbox?
}
}
sorted:
public class AphabeticalOrder {
static {
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
WebDriver driver = new ChromeDriver();
driver.get("file:///C:/Users/SATEESH/Desktop/Hotel.html");
WebElement mtrlist = driver.findElement(By.id("mtr"));
Select s = new Select(mtrlist);
List<WebElement> allOpt = s.getOptions();
for(int i =0;i<allOpt.size();i++) {
String text = allOpt.get(i).getText();
al.add(text);
}
Collections.sort(al);
System.out.println(al);
for(int i=0; i<al.size();i++) // to print vertically
{
System.out.println(al.get(i));
}
driver.close();
}
}
---------------------------------------------------------------------------------------
Using treeset:
}
}
{in hashSet we can’t use normal for loop for ascending order since it
doesn’t preserve the insertion order and we can’t use index value, whereas
in arraylist we can use normal for loop }
*Q: WaS to select all the options in the MTR listbox and deselect them in
reverse order?
Handlings Pop-ups
Solution:
driver.get("https://www.seleniumeasy.com/test/javascript-alert-box-demo.html");
driver.findElement(By.xpath("//button[@class='btn
btn-default']")).click();
WebDriverWait wait= new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
String text = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
/*[
Alert a = driver.switchTo().alert();
String text = a.getText();
a.accept();
// since we are using driver.switchTo().alert() multiples times, so to use easily we
will store it in a variable
] */
System.out.println(text);
driver.close();
}
}
Note: if the popup is alert then there will be no difference between accept and
dismiss, both will click on the OK button only.
Hidden division or calendar popup
Characteristics:
1. We can’t move this popup.
2. We can inspect this popup.
Solution:
1. We handle this popup by using findElement().
Example:
public class HiddenAlert {
static {
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("https://www.flipkart.com/");
Thread.sleep(3000);
driver.findElement(By.xpath("(//button)[2]")).click();
driver.close();
}
}
Assignment
1. Automate the following scenario
a. Open the browser
b. Enter the URL
(https://www.careinsurance.com/rhicl/proposalcp/renew/index-c
are)
c. Enter the policy no. as 123
d. Click on DOB
e. Select your DOB
f. Enter you contact no. as 9845798457
g. Click on lets renew button
public class CareInsuranceHiddenDivision {
static {
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.careinsurance.com/rhicl/proposalcp/renew/index-care");
driver.findElement(By.className("form-control")).sendKeys("123");
driver.findElement(By.id("dob")).click();
WebElement mon =
driver.findElement(By.className("ui-datepicker-month"));
Select s = new Select(mon);
s.selectByValue("11");
WebElement year =
driver.findElement(By.className("ui-datepicker-year"));
Select s1 = new Select(year);
s1.selectByValue("1996");
driver.findElement(By.xpath("//a[.='14']")).click();
driver.findElement(By.id("alternative_number")).sendKeys("9854798547");
driver.findElement(By.id("renew_policy_submit")).submit();
}
}
Characteristics
1. We can move this popup.
2. We can’t inspect this popup.
3. This popup will have an Open and cancel Button.
4. Title of the popup will be either Open or File upload.
Type this HTML code on the notepad and save it on the desktop.
<input type="file" id="cv"/>
Solution:
a. To handle file upload popup we specify the absolute path of the file
as an argument for sendKeys().
b. sendKeys() should be used for the element on which if we click,
which displays the popup.
Example:
*Assignment
2. Write a script to login to naukri.com and upload your resume into it?
public class NaukriResume {
static{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("https://www.naukri.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("login_Layer")).click();
driver.findElement(By.xpath("//input[@placeholder='Enter your active
Email ID / Username']")).sendKeys("[email protected]");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("Vijaya30@"
);
driver.findElement(By.xpath("//button[@type='submit']")).submit();
driver.findElement(By.xpath("//div[text()='UPDATE
PROFILE']")).click();
Thread.sleep(3000);
File f = new File("./data/Resume.docx");
String abspath = f.getAbsolutePath();
driver.findElement(By.xpath("(//input[@class='fileUpload
waves-effect waves-light btn-large'])[1]")).sendKeys(abspath);
}
}
=======================================
[ Robot is a class
keyPress is a non-static method present in robot class.
Keyevent is a static method having all the characters as constant.
We can enter all the char by:
robot r= new robot();
keyPress( KeyEvent.VK_Q);
Robot class is a java class present in java.awt package (abstract window toolkit)
We use robot class whenever we want to perform any keyboard operations in
windows.
In robot class we commonly use two methods
1. keyPress()
2. keyRelease()
Robot class works similar to sendKeys().
}
}
Note:
Runtime is a java class and it is a singleton class. Singleton class means it will
allow you to create only one object at any instance of time.
Solution:
1. By using Robot Class.
Print popup
Characteristics with respect to firefox
1. We can move this popup.(we can’t move this popup in newer version)
2. We can’t inspect this pop.
3. It will have a print and cancel button.
Solution
1. We handle this popup by using Robot class.
Note:
We use Robot class to handle print popups in all the browsers except chrome.
In the chrome browser we inspect the print button(elements) so we handle it by
using findElement().
Assignment
1: Automate the following scenario
1. Open the firefox browser.
2. Go to the download page of selenium.
3. Click on the link 3.141.59 under the latest stable version of selenium
grid.
4. Click on the save file button on the popup.
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("Vijaya30@"
);
driver.findElement(By.xpath("//button[@type='submit']")).submit();
driver.findElement(By.xpath("//div[text()='UPDATE
PROFILE']")).click();
driver.findElement(By.xpath("//i[@title='Click here to download your
resume']")).click();
Thread.sleep(2000);
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_S);
r.keyRelease(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
}
Characteristics
1. We can’t move this popup.
2. We can’t inspect this popup.
3. This popup has an allow and block button.
4. It will be displayed below the address bar in the beginning.
Solution
1. In order to handle this popup we change the settings of the browser, so
that notification popup will not be displayed.
2. To change the settings of the browser we use addArguments() of the
ChromeOptions class.
Note
addArguments() is an example for method overloading.(where it takes string or
list<string> as an argument).
For every browser we have respective Options classes like FirefoxOptions,
internetExplorerOptions, OperaOptions etc.
In order to open the browser in modified settings we use parameterised
constructor in each browser class.
new ChromeDriver() ------ opens the browser in default settings
new ChromeDriver(option) ------ opens the browser in modified settings.
Solution
We handle this popup by sending username and password along with the URL
inside the get().
Test Data:
Username: admin
Password: admin
https://the-internet.herokuapp.com/basic_auth
driver.get("https://admin:[email protected]/basic_auth");
}
}
Child window popup or child browser popup
Characteristics
1. We can move the popup.
2. We can inspect the popup.
3. This popup has minimize, maximize and close the button along with the
address bar.
Solution
1. To handle this popup we use getWindowHandle() , getWindowHandles()
and driver.switchto().window() statement.
Note
- Address of the browser present on the desktop is called windowHandle
(session id).
- In order to retrieve it we use getWindowHandle() .
Q: write a script to print all the windowHandles present in the naukri .com?
public class NaukriChildWindows {
static{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.naukri.com/");
Set<String> allWh = driver.getWindowHandles();
int count = allWh.size();
System.out.println(count);
for(String text:allWh)
{
System.out.println(text);
}
driver.quit();
}
}
Q: What is the difference between getWindowHandle() and
getWindowHandles() ?
getWindowHandle() getWindowHandles()
Q: WAS to get the titles of all the browsers opened by the naukri.com ?
public class GetTitleOFChildWindows {
static{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.naukri.com/");
Set<String> allWh = driver.getWindowHandles();
for(String text:allWh) {
driver.switchTo().window(text); // here we are switching the
control to all the browsers opened.
System.out.println(driver.getTitle()); // printing the title of the
browsers
}
driver.quit();
}
}
**Q: WAS to close all the browsers present in naukri.com without using
quit()?
**Q: WAS to close all browsers except the parent browser in naukri.com?
public class CloseOnlyChildBrowsers {
static{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.naukri.com/");
Set<String> allWh = driver.getWindowHandles();
String parent = driver.getWindowHandle();
for(String wh:allWh) {
driver.switchTo().window(wh);
if(parent.equals(wh)) {
}
else
driver.close();
}
}
}
**Q: WAS to close all the browsers except the specific browser?
Or
WAS to close only the specific browser?
}
Summary of the PopUps
Popup Solutions
Handling tabs
In selenium Tab is also treated as a window. Here we are going to handle the tab
in the same way as we handled child window or child browser popup.
Q: WAS to count the number of tabs present in the browser after clicking
actiTIME inc. link ?
Q: How do you close all the tabs without using quit() after clicking the
actiTIME Inc. link ?
public class HandlingTabs {
static{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/login.do");
driver.findElement(By.linkText("actiTIME Inc.")).click();
Set<String> allWh=driver.getWindowHandles();
int count = allWh.size();
System.out.println(count);
for(String allTabs:allWh) {
driver.switchTo().window(allTabs);
driver.close();
}
}
}
Assignment
1. WAS to print the title of all the tabs opened by the browser after
clicking actiTIME Inc. ?
public class actiTimeTitles {
static{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/login.do");
driver.findElement(By.linkText("actiTIME Inc.")).click();
Set<String> allWh=driver.getWindowHandles();
for(String title:allWh) {
driver.switchTo().window(title);
System.out.println(driver.getTitle());
}
}
}
*Q: WAS to close the child tab 1st then the parent tab by using an iterator?
Assignment
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("manager");
driver.findElement(By.xpath("//div[text() ='Login ']")).click();
driver.findElement(By.xpath("(//div[@class='popup_menu_icon'])[4]")).click();
driver.findElement(By.linkText("About your actiTIME")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//a[contains(.,'Read Service
Agreement')]")).click();
Set<String> wh = driver.getWindowHandles();
int count = wh.size();
System.out.println(count);
for(String agtab:wh) {
driver.switchTo().window(agtab);
}
List<WebElement> headings =
driver.findElements(By.xpath("//h2"));
for(WebElement allHeadings:headings)
{
System.out.println(allHeadings.getText());
}
driver.quit();
}
}
driver.findElement(By.xpath("//p[contains(.,'Bangalore')]")).click();
driver.findElement(By.xpath("(//input[@placeholder='Any
worldwide city or airport'])[2]")).sendKeys("GOI");
driver.findElement(By.xpath("//p[contains(.,'Goa')]")).click();
driver.findElement(By.xpath("//div[@class='flex flex-middle
p-relative homeCalender']")).click();
driver.findElement(By.xpath("//div[@aria-label='Thu Sep 30
2021']")).click();
driver.findElement(By.xpath("//button[.='Search
flights']")).click();
List<WebElement> flights =
driver.findElements(By.xpath("//img[@class]"));
List<WebElement> time =
driver.findElements(By.xpath("//img[@class]/../../../../../../../../div/div/div/div[2
]/div/div[1]/p"));
int count = flights.size();
int count1 = time.size();
System.out.println(count+" "+ count1);
for(int i=0;i<count;i++ ) {
String allflights = flights.get(i).getAttribute("alt");
String deptTime = time.get(i).getText();
System.out.println("Flight_name: " + allflights
+"--->"+"Departure_time: "+deptTime);
}
}
}
Handling Mouse Actions:
driver.get("http://www.dhtmlgoodies.com/submitted-scripts/i-google-like-drag-drop
/index.html");
WebElement source = driver.findElement(By.xpath("//h1[.='Block
1']"));
WebElement target = driver.findElement(By.xpath("//h1[.='Block
4']"));
Thread.sleep(3000);
Actions a = new Actions(driver);
a.dragAndDrop(source, target).perform();
}
}
Handlings Frames
-A web page inside another web page is called an embedded web page (frames).
-Developers create embedded web pages using the iframe tag.
Note
In order to validate the javascript program inspect the element and click on the
console tab in developer toolbar and type this script
document.getElementById('d2').value ='manager'
Scrolling
Note
scrollTo - it will scroll or it will consider from the top of the webpage always.
scrollBy- it will scroll from wherever the scroll bar or control is present.
Testing the application with multiple data which is kept in external resource files
like Excel, Property file, Database etc. is called data driven testing.
public class DemoMaps {
LIST
URL 0
Username 1
Password 2
LIST
URl 0
Username 1
Password 3
Note
- If we use index we will not retrieve the same data if any data is added or
deleted tomorrow.
- we get the same output if new data is added or deleted in future, if we use a
Key-Value pair of matches.
- Same concept is used to store data in property files.
- As per the rule of automation test data should not be Hardcoded within the test
script, because modification and maintenance of test data is difficult. So we use
external resource files like property files, excel, databases etc.
- Property file is used to store the common data. Inorder to create the property
file enter the below data in the notepad and save it as any filename with .property
extension.
url https://demo.actitime.com
username admin
password manager
email [email protected]
- In property file data will be stored in the form of Key-Value pair, KEY and
VALUE should be separated by single space.
- By default all the data available in the property file is a String.
*Q: WAS to login to actiTIME application by taking the test data from the
property file.
Whenever we want to read the data from Excel we need to use Apache POI
plugin or third party tool, so that we can read or write the data from all microsoft
documents like .xls, .xlsx, .docx, .ppt, .outlook etc.
-Apache poi is a free and open source library tool similar to selenium.
wb.getSheet("CreateCustomer").getRow(1).getCell(4).setCellValue("fail");
// convert the java representative object into physical file format
FileOutputStream fos = new
FileOutputStream("./data/testscript.xlsx");
// save the workbook or file (actual writing happens here)
wb.write(fos);
// close the workbook or file
wb.close();
}
}
Note
- Whenever we are reading the data form the excel the extension should be .xlsx
- All the apache file classes should be imported from
org.apache.poi.ss.usermodel package.
- While writing the data back to excel, a specific excel file should be closed, i.e,
you should close the file before doing any modification.
Assignment
1. Do the above program using nested for(i,j)
Generic library
package com.sateesh.generic;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
/**
* this is a generic class for data driven testing
* @author SATEESH
*
*/
public class FileLib {
/**
* This is the generic method to read the data form the property file
* @param args
* @throws IOException
*/
public String getPropertyData(String key) throws IOException {
FileInputStream fis = new
FileInputStream("./data/commondata.property");
Properties p = new Properties();
p.load(fis);
String data = p.getProperty(key);
return data;
}
/**
* this is the generic method to read the data from Excel file
* @throws IOException
* @throws EncryptedDocumentException
*
*/
public String getExcelData(String sheetname, int row, int cell) throws
EncryptedDocumentException, IOException {
FileInputStream fis = new FileInputStream("./data/testscript.xlsx");
Workbook wb = WorkbookFactory.create(fis);
String data =
wb.getSheet(sheetname).getRow(row).getCell(cell).getStringCellValue();
return data;
}
/**
* this is the generic method to write the data into the Excel file
* @param sheetname
* @param row
* @param cell
* @param value
* @throws EncryptedDocumentException
* @throws IOException
*/
public void setExcelData(String sheetname,int row, int cell, String value)
throws EncryptedDocumentException, IOException {
FileInputStream fis = new FileInputStream("./data/testscript.xlsx");
Workbook wb = WorkbookFactory.create(fis);
wb.getSheet(sheetname).getRow(row).getCell(cell).setCellValue(value);
FileOutputStream fos = new
FileOutputStream("./data/testscript.xlsx");
wb.write(fos);
wb.close();
}
}
package com.sateesh.generic;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
1. J unit (java)
2. N unit (.net)
3. PyDev (python)
4. RSPC (Ruby)
5. testNG
testNG is a unit testing framework tool which is mainly used for Batch execution.
Basically testNG is used by the developers to perform unit testing and it is also
used by automation engineers to perform black box testing
Or
testNG is a plugin for eclipse which is inspired by Junit and Nunit with some
additional features.
Note
After the TestNG installation to the eclipse, add the TestNG library (jar) to the
java project as well.
-right click on the java project, go to Build path and select Add Libraries.
- select testNG and click on Next and Finish.
- it will display the TestNG folder in the java project.
package com.actitime.testscript;
import org.testng.Reporter;
import org.testng.annotations.Test;
Q.If a class contains multiple test methods in which order they are
executed?
Alphabetical order.
Example:
@Test(priority =3)
public void modifyCustomer() {
Reporter.log("modifyCustomer",true);
}
Batch Execution
Executing multiple test classes or test scripts is called batch execution.
Or
Executing all of them together via testng.xml file is called batch execution.
TestNG suit
- Testng suit is an xml file which contains a list of testng classes (test classes)
which are to be executed.
- Testng classes are the test classes which means a class contains @Test
annotation or test method.
- Test methods means a method which has @Test annotation is called test
method.
- To create the suit file follow the below steps:
1. Write click on java project.
2. Go to testng and select convert to testng.
3. Click on finish. It will create a suit file called testng.xml .
To execute it:
1. Right click on testng.xml file (suit file).
2. Go to run as and select testng suit.
Or
1. Open the suit file and click on the run button.
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="qsp.DemoA"/>
<class name="com.actitime.testscript.ProjectModule"/>
<class name="com.actitime.testscript.Demo"/>
<class name="com.actitime.testscript.CustomerModule"/>
<class name="com.actitime.testscript.TaskModule"/>
</classes>
</test>
</suite>
Q: How do you execute only the failed test cases or test methods?
By using testng-failed.xml file present under test output folder.
@Test(dependsOnMethods ="createTask")
public void modifyTask() {
Reporter.log("modifyTask",true);
}
@Test(dependsOnMethods= {"createTask","modifyTask"})
public void deleteTask() {
Reporter.log("deleteTask",true);
}
}
Output
createTask
createTask
createTask
modifyTask
deleteTask
Assertion
Assertion is one of the features available in testng which is used to verify the
expected result of the test script.
Note
As per the rule of automation every expectation should be verified with assert
statement instead of java if else, because if else doesn’t have the capacity to fail
the test script.
There are 2 types of assert statement available in testng
1. asser(HardAssert)
2. SoftAssert
Note
* If the comparison fails then the statements which are present after the Assert
statement of the current test method will not be executed.
*In the above example it will not close the browser if the comparison fails.
*In order to continue the execution even after failure of the comparison, we can
use SoftAssert, but here all the methods are non static (both have same number
of methods except assertAll() )
public class Assertion {
static {
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
@Test
public void testVerifyTitle()
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
String expectedTitle = "Soogle";
String actualTitle = driver.getTitle();
SoftAssert s = new SoftAssert();
s.assertEquals(actualTitle, expectedTitle);
driver.close();
s.assertAll();
}
}
Note
* To update the status of the information into the result window we should use
assertAll() at the last.
* Any statements after assertAll() will not be executed if the comparison fails.
1.All the methods are static 1.All the methods are non static.
Annotation
Annotation is the metadata which is used to provide special instruction to the java
compiler during run time.
Optional annotations
@DataProvider
@Listeners
@Parameters
@AfterGroups
@BeforeGroups
@Factory
@ignore -----> it will ignore the test script --skips
@Notifications
@ObjectFactory
@TestInstance
------------------------------------------------------------------------------------------------------
public class CustomerModule {
@BeforeClass
public void openBrowser() {
Reporter.log("openBrowser",true);
}
@AfterClass
public void closeBrowser() {
Reporter.log("closeBrowser",true);
}
@BeforeMethod
public void login() {
Reporter.log("login",true);
}
@AfterMethod
public void logout() {
Reporter.log("logout",true);
}
@Test(priority=1,invocationCount=2)
public void editCustomer() {
Reporter.log("editeCustomer",true);
}
@Test
public void registerCustomer() {
Reporter.log("registerCustomer",true);
}
@Test
public void deleteCustomer() {
Reporter.log("deleteCustomer",true);
}
}
Output
openBrowser
login
deleteCustomer
logout
login
registerCustomer
logout
login
editeCustomer
logout
login
editeCustomer
logout
closeBrowser
@BeforeMethod
BeforeMethod annotation will be executed before executing every test
method(@Test) present in the class.
In real time the before method will be used to develop common pre conditions
which is required for all the test scripts like login programs.
@AfterMethod
AfterMethod annotation will be executed after executing every @Test method in a
class.
In real time it is used to develop common post conditions like logout programs.
@BeforeClass
BeforeClass annotation will be executed before executing every test class.
In real time, a before class method will be used to open the browser.
@AfterClass
AfterClass annotation will be executed after every @Test class.
In real time it is used to close the browser.
@Test
Test annotation indicates the test method.
In real time one test method represents one test script or test case.
BASE CLASS
Generic code:
public class BaseClass {
@BeforeClass
public void openBrowser() {
Reporter.log("openBrowser",true);
}
@AfterClass
public void closeBrowser() {
Reporter.log("closeBrowser",true);
}
@BeforeMethod
public void login() {
Reporter.log("login",true);
}
@AfterMethod
public void logot() {
Reporter.log("logout",true);
}
}
Note
Inorder to use FileUtlis.copyFile statement we need to download commons io jar
from apache commons community
(https://commons.apache.org/proper/commons-io/download_io.cgi)
Click on the above click and under Binaries click on the second link
(https://downloads.apache.org//commons/io/binaries/commons-io-2.11.0-bin.zip)
Extract the zip file and copy the 1st jar file and paste it in the eclipse jar folder.
Add that jar file to the build path.
Assignment
Use generic code in base class to enter UN and Pwd in actiTime.com
driver.findElement(By.xpath("//input[@type='password']")).sendKeys(f.getPropert
yData("password"));
driver.findElement(By.xpath("//div[text() ='Login ']")).click();
}
@AfterMethod
public void logot() {
Reporter.log("logout",true);
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("logoutLink")).click();
}
}
Listeners
* Listener is a feature available in testng which is used to monitor test execution
in runtime and perform appropriate action or operation whenever the test case is
getting failed or passed or skipped etc.
* Whenever we want to implement the listener feature, we should create a class
which implements ITestListener and provide implementation (override) to all the
methods present in ITestListener.
@Override
public void onTestStart(ITestResult result) {
}
@Override
public void onTestSuccess(ITestResult result) {
}
@Override
public void onTestFailure(ITestResult result) {
String test = result.getName();
TakesScreenshot t = (TakesScreenshot) driver;
File src = t.getScreenshotAs(OutputType.FILE);
File dest= new File("./Screenshot/"+test+".png");
try {
FileUtils.copyFile(src, dest);
}
catch(IOException e) {
}
}
@Override
public void onTestSkipped(ITestResult result) {
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
@Override
public void onTestFailedWithTimeout(ITestResult result) {
}
@Override
public void onStart(ITestContext context) {
}
@Override
public void onFinish(ITestContext context) {
}
}
@Listeners(com.sateesh.generic.ListenerImplementation.class)
public class CustomerModule extends BaseClass {
@Test
public void createCustomer() {
Reporter.log("createCustomer",true);
Assert.fail();
}
Group Execution
* Executing the collection of similar test scripts is called group execution.
* In automation regression suite will be divided into two types
1. Smoke test scripts
2. Regression test scripts
* In order to achieve smoke testing we go for group execution of testng.
* In order to achieve group execution every test script should have a group name
along with @Test, one script can have multiple group names.
Example: @Test(groups=”RegressionTest”)
@Test(groups={“RegressionTest”,”SmokeTest”})
* We should declare a group key within the testng.xml file.
* Group key should be declared before the test tag and after the suite tag (as
shown below).
programm
In case of group execution every configuration method should have group names
otherwise those configuration methods or annotations will not be executed or will
not participate in the group execution.
Example: @BeforeMethod(groups={“RegressionTest”,”SmokeTest”})
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="com.actitime.testscript.ProjectModule">
<methods>
<include name="createProject"/>
</methods>
</class>
</classes>
</test>
</suite>
Parallel execution
- Executing the multiple test scripts with multiple browsers concurrently or at the
same time is called Parallel execution.
- TestNG provides 2 types of parallel execution
1. Distributed parallel execution.
2. Cross browser testing or compatibility parallel testing.
- If we execute all the 1000 test cases sequentially it may take 20 hours, in order
to get the result in early stages we should customize the testng.xml suite file as
shown in the above diagram.
- In order to achieve distributed parallel execution, create multiple test blocks and
distribute the test scripts and enable the attribute parallel = “tests” in the suite
tag.
- In order to achieve cross browser testing we should create multiple test blocks
and provide browser parameters for each test block as shown in the above
diagram.
- So that when we execute the suite file each test block opens the specific
browser using threads and executes all the test scripts in different browsers at
the same time parallely.
- In case of cross browser testing we should mandatorily use @Parameter
annotation along with @BeforeTest and @AfterTest annotations in the
BaseClass.
- @Parameters annotation will be used to receive browser parameters from the
xml suite file into the BaseClass or test script.
- In real time to perform cross-browser or cross platform testing we go for
Selenium Grid.
- Selenium grid is another tool available in the selenium community which is used
to run in another virtual machine.
@BeforeSuite
@BeforeSuite will be executed before the suite tag present in the testng.xml file
or suite file. In real time it is used to connect to the database if the project
requires DB connection.
@AfterSuite
It will be executed after the suite tag present in the testng.xml file and it is used to
close the DB connection in real time.
@BeforeTest
It will be executed before the test block present in the testng.xml file and it is
mandatory to use in case of parallel execution.
@AfterTest
AfterTest will be executed after the Test block in the suite file.
Encapsulation :
Hiding the data and binding with methods in order to hide the internal
implementation is called encapsulation.
- We achieve this by making the variable private and access outside the class
with the help of getters and setters method.
public class A {
private int i; //declaration
public A() {
i=10; // initialization
}
public int getValue() { // giving only read access
return i;
}
public void setValue(int j) { //giving write access
i=j;
}
}
public class B {
public static void main(String[] args) {
A a1= new A();
int x=a1.getValue(); //utilization
System.out.println(x);
a1.setValue(52); //utilization
System.out.println(a1.getValue());
}
}
Data will be stored in a variable, in java for any given variable we should perform
following steps
1. Declaration
2. Initialization
3. Utilization
There are 2 classes in the above example, the purpose of class A is to only
manage the variable i whereas the purpose of class B is only to execute the
code.
13.10.2021
Prog 1.1:
package qsp;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
Prog 1.2:
package qsp;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
Prog 2.1:
package qsp;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
Prog 2.2:
package qsp;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
-Selenium code to enter valid login and invalid login is(or setLogin()
method can be used to enter valid and invalid input):-
package qsp;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
package com.actitime.testscript;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
-Page Object Model is one of the java design pattern which is used to store the
objects(elements). POM concept is used by the developers to develop the web
page and it is also used by the automation engineers to test the web pages.
-It is also used to avoid StaleElementReferenceException.
-In POM, we declare the element by using @FindBy annotation and we initialise
the element by using PageFactory.initElements() method.
-@FindBy annotation should be imported from org.openqa.selenium.support
package.
-The syntax is:-
Syntax 1:-
@FindBy(Locatorname=”Locator Value”)
private WebElement ElementName;
Syntax 2:-(for multiple elements)
@FindBy(Locatorname=”Locator Value”)
private List<WebElement> ElementName;
-PageFactory.initElements() method will take 2 arguments(parameters)
1. WebDriver(driver)
2. Object of POM class or page class(this)
Note
The class in which elements of the web page are stored by using @FindBy
annotation is called POM class or Page class.
Example : Login page, homepage, task list page etc.
The class which we execute by using @Test (test scripts are written) is called a
test class.
package com.actitime.pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
@FindBy(name="pwd")
private WebElement pwtbx;
@FindBy(xpath="//div[.='Login ']")
private WebElement lgbtn;
----------------------------------
package com.actitime.testscript;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import qsp.LoginPage;
Q: What is the difference b/w Page Object Model and Page Factory ?
Advantages of POM
1.Maintenance of WebElements is easy, since webelements are maintained
based on the page.
2. Modification of webelement locators is easy whenever the UI is changed.
3. We can avoid StaleElementReferenceException.
4. Xpath and locators of the webelements are reusable, so that no need to put
the same effort to rewrite the xpath again.
5. Object repositories can be easily shared across the team members via Github.
***Note
In real time the number of POM classes will be equal to the number of web
pages present in the application.
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class CheckBoxPage {
@FindBy(xpath="//input[starts-with(@type,'checkbox')]")
private List<WebElement> boxes;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import com.actitime.pom.CheckBoxPage;
- Inorder to execute the test script with multiple inputs or test data, we use an
excel and property file, so we call our framework a Data driven framework.
- Inorder to avoid writing repetitive steps again and again we use lots of reusable
methods, so we call our framework a method driven framework.
- Since we maintain our framework module wise, we also call our framework a
Modular driven framework.
- Then it will executes the @Test method where actual test scripts are written in
test script package, while executing the test scripts it will take the test data from
the excel file with the help of Apache POI jars and performs action on the GUi
application by calling necessary methods present in the POM class.
- Once it executes the test method it will execute the Logout code which is
present in @AfterMethod.
- Like this it will execute all the test cases one after the other with help of Batch
runner(testng.xml).
- After the execution of all the test cases it will close the browser which is present
in @AfterClass.
- Since we are using TestNG it will automatically generate the default HTML
report (test-output folder), which contains number of test cases passed, failed
and skipped.
Actitime
|_____Src
| |____com.actitime.generic
| | |_ BaseClass
| | |_FileLib
| | |_ ListenerImplementation
| |____ com.actitime.pom
| | |_ LoginPage
| | |_ HomePage
| | |_ TaskListPage
| |____ com.actitime.testscript
| |_ CustomerModule
| |_ ProjectModule
|____ data
| |____ commondata.preperty
| |____ testscript.xlsx
|____ screenshot
|____ test-output
|____ testng.xml
Github
Github is a decentralized online cloud repository where we can maintain our
entire framework in one place, so that it can be shared easily with multiple
engineers working on the same project in different locations.
Advantages of Github
1. Decentralized repository.
2. Cloud repository.
3. No need for a system engineer to maintain Github.
4. File sharing between the team members will be easier.
5. Master copy of the framework available in the github so that we can
perform batch execution any time.
Experience notes
==========================================================
Xpath axes
Xpath axes are the special keywords of xpath which has following syntax
//axesName :: tag
example - /decedent::a ---> means //a
Axes names:
1. ancestor
2. decedent
3. child
4. parent
5. following-sibling
6. preceding-sibling
table
|_Tr
1 |__ td 2 java
2 |__td 1
3 |__td
4 |__td
5 |__td selenium
1|__a ide
2|__a webdriver
//td[3]/preceding-sibling::td[2] → java
//td[3]/following-sibling::td[2] → selenium
//td[3]/parent::tr
//td[3]/child::a[2]
//td[3]/ancestor::table
//tag[starts-with(text(),’value’)]
//tag[starts-with(@AN ,’AV’)]
Html
|__body
|__table
|__tbody
1 |__tr
1 |__td java
2 |__td 100
2 |__tr
1 |__td selenium
2 |__td 300
Assignment
Q: WAS to print the content of the webtable present in any given website
or URL should be taken from the user.
System.out.println("BookName:"+bookname+"-->"+"BookPrice:"+bookprice);
}
driver.close();
}
}
Q: WAS to click on all the checkboxes present in the given web app or URL
should be taken from the user.
Html code:
c1: <input type="checkbox" /><br>
c2: <input type="checkbox" /><br>
c3: <input type="checkbox" /><br>
c4: <input type="checkbox" /><br>
c5: <input type="checkbox" /><br>
c6: <input type="checkbox" /><br>
c7: <input type="checkbox" />
public class ApexCheckBox {
static {
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("file:///C:/Users/SATEESH/Desktop/checkbox.html");
List<WebElement> boxes =
driver.findElements(By.xpath("//input[starts-with(@type,'checkbox')]"));
int count = boxes.size();
for(int i =0;i<count;i++) {
boxes.get(i).click();
Thread.sleep(1000);
}
for(int i=count-1;i>=0;i--) {
boxes.get(i).click();
Thread.sleep(1000);
}
driver.close();
}
}
driver.findElement(By.xpath("//input[starts-with(@id,'password')]")).sendKeys(Key
s.BACK_SPACE);
Thread.sleep(1000);
}
driver.close();
}
}
Exceptions
=======================================================
1.IllegalStateEcxeption (selenium/unchecked)
We get this exception whenever the path of the driver executable file is not set.
5.TimeOutException (selenium/unchecked)
We get this exception whenever locators are not matching or whenever elements
are not within the specific time given in the explicitWait.
6.UnsupportedOperationEcxeption (selenium/unchecked)
We get this exception whenever we use deSelect() on a single select listbox.
7.UnexpectedTagNameException (selenium/unchecked)
We get this exception whenever we try to pass WebElement to the select class
which is not a type of listbox.
8.NoAlertPresentException (selenium/unchecked)
We get this exception whenever we try to handle the alert popup when the popup
itself is not present.
9. UnhandledAlertException (selenium/unchecked)
We get this exception whenever we try to perform action on the browser without
handling alert popup.
11.WebDriverException (selenium/unchecked)
We get this exception whenever we pass the relative path of the file to the
sendKeys().
Resume Building