0% found this document useful (0 votes)
2 views126 pages

Basic Selenium Notes

The document outlines the content of a basic Selenium course, covering topics such as Selenium architecture, WebDriver methods, and automation testing principles. It discusses the advantages and disadvantages of Selenium, its components, and the differences between JSON Wire Protocol and W3C Protocol. Additionally, it provides an overview of setting up a Maven project and various WebDriver methods for browser automation.

Uploaded by

triple.entropyy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views126 pages

Basic Selenium Notes

The document outlines the content of a basic Selenium course, covering topics such as Selenium architecture, WebDriver methods, and automation testing principles. It discusses the advantages and disadvantages of Selenium, its components, and the differences between JSON Wire Protocol and W3C Protocol. Additionally, it provides an overview of setting up a Maven project and various WebDriver methods for browser automation.

Uploaded by

triple.entropyy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic Selenium Course Content

1 Introduction
2 Selenium Architecture
3 WebDriver Architecture
4 WebDriver Methods
5 Basic HTML
6 Locators
7 WebElement Methods
8 TakesScreenshot
9 Synchronization
10 Select Class
11 Actions Class
12 iFrames
13 Popups
14 JavaScriptExecutor
15 Data Driven testing [DDT]
16 Page Object Model [POM]
17 TestNG [Test Next Generation]
18 Introduction to Maven
19 Introduction to GitHub
20 Introduction to Jenkins
21 Types of frameworks
1. Introduction
Introduction to Automation
What is Automation?
1. Automation is a process of doing things without
human/manual intervention.
2. Automation according to software is making use
of any automation tool to automate a task by
writing test script/program/command.
Need for Automation
1. Suitable for repetitive tasks like Regression
Testing and Smoke Testing.
2. Improves accuracy of testing.
3. Increases productivity.
4. Reduces the overall time taken for the testing
process.
What Cannot Be Automated?
1. OTP / CAPTCHA / QR Code.
2. Virtual keyboards and Biometrics.
3. Audio / Video / Image and Voice commands.
4. Gaming applications.
5. Test cases with improper manual step.

Note: 100% Automation Not Possible.


Why Automation testing?
Manual testing Automation testing
More time consuming. Less time consuming.
More resource required Limited resource
throughout the project. throughout the project.
Monotonous and Tedious Comparatively easy to test
Job to do. the application.
Less accurate. More accurate.
Less test coverage. Test coverage will be more.
Chances for human error. Less chances for human
error.
High investment. Cost efficient.
High flexibility for Best suit for regression /
exploratory / UI testing. stable features.

Introduction to Selenium
What is Selenium?
1. Selenium is a software testing tool / library /
framework developed by Jason Huggins in 2004.
2. It is used to automate web based application.
3. A Group of people / Community which includes
ThoughtWorks, Google, Sauce Labs and other
contributors are involved in development of
Selenium.
Advantage of Selenium
1. It is an Open Source Tool.
2. Supports multiple programming language.
[Java, C#, Python, Ruby, JavaScript & etc.,]
3. Supports multiple operating system.
[Windows, macOS, Linux & etc.,]
4. Supports major browsers.
[Chrome, Firefox, Edge, Safari & etc.,]
5. Supports third party integration.
Disadvantage of Selenium
1. Desktop Application cannot be automated.
2. Mobile Application cannot be automated.
3. No customer support, only community support.
4. 100% automation is not possible.

Why Selenium is preferred?


Selenium QTP
Supports multiple Operating Supports only Windows OS.
Systems.
Supports 14+ Programming Supports only 2 languages:
Languages. JavaScript & VBScript.
Supports multiple browsers on Does not support Safari browser.
multiple OS.
Works on Web Applications. Supports all types of applications.
Open Source. Licensed Tool.
Components of Selenium
2. Selenium Architecture

Selenium Architecture till Version 3:


Why Selenium should follow this architecture?
1. Both client side and server side will not understand
each other's language. So there should be a Standard
protocol to communicate seamlessly.
2. Browsers are more secure that it will not expose 100%
of its service to any third party application.

Difference between JSON Wire Protocol and W3C?


JSON Wire Protocol W3C Protocol
JavaScript Object Notation. World Wide Web Consortium.
It acts as a translator that converts This is an upgraded protocol that
the client's request into HTTP replaces the JSON Wire Protocol.
format and sends it to server.
It identifies and converts the It is a standardized language used to
request to corresponding web structure HTTP requests and
service and sends to the browser responses globally.
driver.
This was the older standard used in It is faster, more secure, and supports
Selenium 3 and earlier versions. better interoperability (the ability for
different systems to work together
smoothly).
It is older and discontinued This is the current standard used in
approach for communication. Selenium 4, as browsers are also
developed by W3C standards, the
"translator" step is no longer needed,
allowing the script to communicate
directly with the driver.
*********Maven Project Setup**********
Steps to Create a Maven Project
1. Open Eclipse IDE.
i. Go to File → New → Maven Project.
ii. Check the box (Create a simple project)
iii. Enter:
a. Group ID → Company/Organiza on Name
[Link] ID → Project Name
iv. Click Finish.
2. Add Dependency:
1. Open Maven Repository. ([Link]
2. Search for Selenium Java.
3. Select the stable version considering recent
release and most no. of usage.
4. Copy dependency code.
5. Paste it under dependencies in [Link] file.

1. Maven will give good


folder structure for
project.
2. Maintain all the test
scripts in src/test/java
folder.
3. [Link] will store all
maven dependencies.
3. WebDriver Architecture
(Selenium WebDriver Hierarchy / Selenium Architecture
WTO Java / Selenium 4 class diagram)

Launching Browsers in Selenium


FirefoxDriver driver = new FirefoxDriver(); //Firefox Browser
ChromeDriver driver = new ChromeDriver(); //Chrome Browser
EdgeDriver driver = new EdgeDriver(); //EdgeDriver

//upcasting but restricting code to a concrete class that


will lose benefits of programming to WebDriver interface
RemoteWebDriver driver = new ChromeDriver();
First Line of code
WebDriver driver = new ChromeDriver(); //Upcasting

Upcasting:
Converting a child class object to a super type.
Important interface in Selenium is WebDriver.

Advantage of upcasting:
1. Code Optimization.
2. Achieve cross browser testing.
3. Runtime polymorphism.
4. Same script can run on multiple browsers.
Note:
SessionNotCreatedException -> browser version and
browser driver version mismatching.
IllegalStateException -> browser driver might not be
analyzed by Selenium.
SearchContext Interface
 It is the super-most interface in Selenium.
 It provides mechanism to locate or identify components
on the web page. [It only knows how to "find" things]
 It consist of 2 abstract non-static methods,
1. findElement(By)
2. findElements(By)

TakesScreenshot Interface
 It is an interface in Selenium.
 It provides mechanism to capture screenshot.
 It has only one abstract non-static method,
1. getScreenshotAs()

JavaScriptExecutor Interface
 It is also an interface in Selenium.
 By using JavaScriptExecutor, we can execute
JavaScript code on web page from Selenium.
 It consist of 2 abstract non-static methods,
1. executeScript()
2. executeAsyncScript()
WebDriver Interface
 It is an important interface in Selenium.
 It Extends SearchContext and it is being implemented by
the RemoteWebDriver class.
 Provides methods to perform driver actions.
 It has 11 inbuilt abstract non static methods and 2
inherited methods from SearchContext interface,
In built WebDriver methods
1. get(String url) 9. getWindowHandle ()
2. getTitle() 10. getWindowHandles ()
3. getCurrentUrl() 11. switchTo()
4. getPageSource()
5. close() Inherited methods
6. quit() 1. findElement(By)
7. manage() 2. findElements(By)
8. navigate()

RemoteWebDriver Class
1. It is the implementation class for all the
interfaces in Selenium.
2. It executes commands on a remote server or a
Selenium Grid via network communication. [It is
the actual machine built from that blueprint].
3. All browser specific classes are extending
properties from RemoteWebDriver class.
ChromeDriver, EdgeDriver, FirefoxDriver, SafariDriver
1. These are the Browser-specific classes that is
extending RemoteWebDriver class.
2. These classes act as a wrapper to ensure your
commands follow the W3C protocol, which is
the universal browser automation standard.
4. WebDriver Methods
1. get(String url)
1. This method is used to navigate to the particular
webpage by entering the URL.
2. It takes String URL as the argument and it should
be a fully qualified URL. If partial URL is passed
InvalidArgumentException will occur.
3. Return type is void.

Syntax:
[Link](“FullyQualifiedURL”);

2. getTitle()
1. This method is used to capture the title of the
current web page. It can be used for validation.
2. It does not take any arguments.
3. Return Type is String.
Syntax:
[Link]();
3. getCurrentUrl()
1. This method is used to capture the url of the
current web page. It can be used for validation.
2. It does not take any arguments.
3. Return Type is String.
Syntax:
[Link]();

4. getPageSource()
1. This method is used to capture the source code
of the current web page.
2. It does not take any arguments.
3. It can be used for validation.
4. Return Type is String.
Syntax:
[Link]();

5. close()
1. This method is used to close the current web
page where the driver control is present.
2. It does not take any arguments.
3. Return Type is void.
Syntax:
[Link]();
6. quit()
1. This method is used to close the entire
browser and terminates browser connection.
2. It does not take any arguments.
3. Return Type is void.
Syntax:
[Link]();

7. manage()
1. This method is used to manage configurations
of browser related operational settings like
window dimensions and position, handle
browser cookies, & timeout durations.
2. Return Type is Options.

Options
1. Options is an interface in Selenium, it can
control the operational behaviors of the
browser window.
2. Options interface contains several methods
that further returns few other interfaces,
a. window() - Window
b. timeouts() - Timeouts
c. cookies() - Cookies
d. logs() - Logs.
1. window()
1. It is a method present in Options interface.
2. It acts as a gateway/bridge to control the size,
position, and visibility state of the current
browser.
3. It does not take any arguments.
4. It returns Window. Window is an interface in
Selenium.

Window
1. It is an interface in Selenium that provides
methods to control the physical properties of
the browser window during automation.
2. It consist of several method that will help in
changing the dimension and coordinates of the
browser window,
I. maximize()
II. minimize()
III. fullscreen()
IV. getSize()
V. setSize(Dimension dimension)
VI. getPosition()
VII. setPosition(Point position)
I. maximize()
1. This method is used to expand the browser
window. It is the second line of code.
2. It does not take any arguments.
3. Return type is void.
Syntax:
[Link]().window().maximize();

II. minimize()
1. This method is used to minimize the
browser window.
2. It does not take any arguments.
3. Return type is void.
Syntax:
[Link]().window().minimize();

III. fullscreen()
1. This method is used to expand the browser
window to full screen view.
2. It does not take any arguments.
3. Return type is void.
Syntax:
[Link]().window().fullscreen();
IV. getSize()
1. This method is used to capture the height
and width of the current window.
2. It does not take any arguments.
3. Return type is Dimension.
Syntax:
[Link]().window().getSize();
Dimension:
 It is a class in Selenium, is used to handle the
height and width of the current window. It is a
template used to create object with height and
width.
 It has 2 methods, getHeight() & getWidth().
 Return type of these methods is int.
Syntax:
Dimension dimension = new Dimension(int, int);

V. setSize(Dimension dimension)
1. This method is used to set the size (height
and width) of the current browser window.
2. It takes Dimension as arguments. Create
object and pass the reference as the
argument.
3. Return type of setSize() is void.
Syntax:
Dimension dimension = new Dimension(intW, intH);
[Link]().window().setSize(dimension);

VI. getPosition()
1. This method is used to capture the current
position(X & Y coordinates) of browser.
2. It does not take any arguments.
3. Return type is Point.
Syntax:
[Link]().window().getPosition();

Point:
1. It is a class in Selenium, it is used to handle X
and Y coordinates of the current window.
2. It is used to create object with X & Y coordinates.
3. It has 2 methods, getX() & getY().
4. Return type of getX() & getY() is int.
Syntax:
Point point = new Point(intX, intY);

VII. setPosition(Point position)


1. This method is used to set the position(X & Y
coordinates) of current browser window.
2. It takes Point as arguments. Create object
for Point class present in Selenium and pass
the reference as the argument.
3. Return type is void.
Syntax:
Point point = new Point(intX, intY);
[Link]().window().setPosition(point);

8. navigate()
1. This method is used to navigate the browser
window / application.
2. It does not take any arguments.
3. Return Type is Navigation.
Navigation
1. It is an interface in Selenium, is used to handle
browser related navigation operations like
forward, backward and refresh.
2. It consist of few methods, that are used to
perform the operation,
a. back()
b. forward()
c. refresh()
d. to(String Url)
e. to(URL Url)
a. back()
1. This method is used to perform back operation
on the browser.
2. It does not take any arguments.
3. Return type is void.
Syntax:
[Link]().back();

2. forward()
1. This method is used to perform forward
operation on the browser.
2. It does not take any arguments.
3. Return type is void.
Syntax:
[Link]().forward();

3. refresh()
1. This method is used to perform refresh
operation on the browser.
2. It does not take any arguments.
3. Return type is void.
Syntax:
[Link]().refresh();
4. to(String URL)
1. It is another way to launch to the url/applicaiton.
2. This method is used to navigate to a particular
URL without using get(String Url).
3. It takes String url as argument.
4. Return Type is void.

Syntax:
[Link]().to(“StringUrl”);

5. to(URL Url)
1. This method is also used to navigate to a
particular URL without using get(String Url).
2. It takes URL class as arguments.
URL:
1. URL is a class in java.
2. It is used to point to a particular resource.
3. It is also used to convert the String data into
URL format.
4. To access we need to create object and pass
String argument into the constructor.
5. Uniform Resource Locator is the abbreviation
of URL.
Syntax:
URL url = new URL(“String url”);
Syntax for to(URL Url):
URL url = new URL(“String url”);
[Link]().to(url);
or
[Link]().to(new URL(“String url”));

9. getWindowHandle()
1. This method is used to capture the session id
of the current window.
2. It does not take any arguments.
3. Return type is String.
Syntax:
[Link]();

10. getWindowHandles()
1. This method is used to capture multiple
session ids of the current window.
2. It does not take any arguments.
3. Return type is Set<String>.
Syntax:
[Link]();
11. switchTo()
1. This method is used to transfer the driver
control from one place to another place.
2. It includes,
a. window to window
b. window to frame
c. window to alert
3. It does not take any arguments.
4. Return Type is TargetLocator.

TargetLocator:
It is an interface in Selenium.
It has the methods to transfer the driver control from
1. window ---- to ---- window
2. window ---- to ---- frame
3. window ---- to ---- alert
5. Basic HTML
What is HTML?
1. HTML stands for HyperText Markup Language.
2. It is used to develop the front end of every web
page / web application.
3. Selenium WebDriver interacts with web
elements by referring to their HTML code.
4. It contains full of pre-defined tags which has
dedicated purpose.
5. There are 2 types of tags available in HTML,
a. Paired tag b. Unpaired tag
6. There are 3 main components in HTML,
a. Tag b. Attribute c. Text
7. HTML code starts with the tag <html> and ends
with </html> [It is a paired tag]
8. All the code present between <body> and
</body> will be displayed inside view port area.
Example HTML Code
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<p>HTML</p>
<br>
<a href="[Link]/">click here</a>
</body>
</html>

Login Page
<html>
<head><title>Login Page</title> </head>
<body>
<input type="text" placeholder="Username"/>
<br>
<input type="password" placeholder="Password"/>
<br>
<input type="button" value="Login"/>
</body>
</html>
To create links & images
<html>
<head>
<title>Links & Images</title>
</head>
<body>
<img src="[Link]" alt="Logo Image"><br>
<ahref="[Link]/">Facebook</a><br>
</body>
</html>

To create a dropdown
<html>
<head><title>Dropdown Example</title></head>
<body>
<select>
<option>- Select Country -</option>
<option>India</option>
<option>Pakistan</option>
<option>Sri Lanka</option>
……
</select>
</body>
</html>
Points to remember as an Automation Test
Engineer while working with HTML:
Point 1: Anything comes after ‘<’ is called as Tag.
Example:
<input type="password" placeholder="Password"/>

Point 2: Any value separated using ‘=’ is called as


Key & Value Pair.
Example:
<input type="password" placeholder="Password"/>
<input type="password" placeholder="Password"/>

Point 3: Anything present in between ‘>’ & ‘<’ is


called as text/visible text.
Example:
<ahref="[Link]/">Facebook</a>
<option>India</option>
2 Inherited Methods from SearchContext:

1. findElement(By by)
1. This method is used to identify / locate the
first matching web element in the web page.
2. It takes By type argument.
3. Return type is WebElement.
Syntax: [Link](By);

2. findElements(By by)
1. This method will identify all the matching web
elements present in one go with same
characteristics.
2. It takes By type argument.
3. Return type is List<WebElement>.
Syntax: [Link](By);

Note:
 Set<> stores only the unique values.
 List<> can store duplicate values also.
By
1. By is an abstract class in Selenium.
2. All the locator methods are described as static
methods in By class,
1. id(String id)
2. name(String name)
3. className(String className)
4. linkText(String linkText)
5. partialLinkText(String partialLinkText)
6. tagName(String tagName)
7. cssSelector(String cssSelector)
8. xpath(Stirng xpath)

3. Purpose of all these methods is to decide how


to search for any component on the web page.
4. All of these takes String as an argument.
5. All the methods present inside By class returns
instance of By itself.
6. Locators
1. Locators are identifiers that are used to find
specific component on web page like buttons,
text boxes, or links and etc., using HTML tags,
attributes and text.
2. Locators are used to identify and access web
elements on the view port area.
3. All locators are provided as static methods inside
the By class in Selenium.
4. Locators are used in conjunction with
findElement() or findElements() methods.
5. There are 8 types of locators available,

Direct Locators
1. id
2. name
3. linkText
4. partialLinkText
5. className
6. tagname

Expression based Locators


1. cssSelector
2. xpath
1. id(String id)
1. id locates the element using id attribute.
2. It is the Fastest and most preferred locator among all.
3. It should be given the first priority.
Syntax:
[Link]([Link]("username"));

Note:
1. findElement(By) & findElements(By) will attempt
locating the web element only once.
2. If the element is located/identified,
findElement(By) will return WebElement and
findElements(By) will return List<WebElement>.
3. If the element is not located findElement(By) will
throw NoSuchElementException and
findElements(By) will return Empty List.

2. name(String name)
1. name locates the element using the name attribute.
2. Commonly used when id attribute is not available.
3. It should be given second priority.
Syntax:
[Link]([Link]("password"));
3. className(String classValue)
1. ClassName locates element using class attribute.
2. It is the least recommended method.
3. ClassName is compound, dynamic & alphanumeric.
Syntax:
[Link]([Link]("btn_A34RRv#"));

4. linkText(String linkText)
1. linkText locates the element using the exact
visible text.
2. If there is any text present in <a> (hyperlinks),
then linkText strategy can be used.
Example: <a href=”[Link]”>Facebook</a>
Syntax:
[Link]([Link]("Facebook"));

5. partialLinkText(String partialLinkText)
1. partialLinkText locates a link by partial match of
the visible text.
2. If there is any text present in <a> (hyperlinks)
and the text is too long, then partialLinkText
strategy can be used.
partialLinkText can be used when,
3. The visible text is very lengthy.
4. The text is partially dynamic.
5. The text contains blank spaces at the end or
at the beginning.
Example: <a href=”[Link]”>Add To Cart</a>

Syntax:
[Link]([Link]("Add"));

6. tagName(String tagName)
1. tagName locates elements by HTML tag name.
2. Rarely used alone, but useful for lists
(e.g., find all <a>, <input>, <div>&<button>).
Syntax:
[Link]([Link]("button"));

7. cssSelector(String cssSelector)
1. cssSelector locates elements by CSS Expressions.
2. It is very powerful and faster than xpath.
3. CSS means Cascading Style Sheet used to design
webpage.
4. cssSelector can be used with attributes only. At
least one attribute should be present.
(e.g., find all <a>, <input>, <div>&<button>).
Expression Syntax:
1. [attributeName='attributeValue']
2. tagname[attributeName='attributeValue']
Example:
<input type = “text” id = “abc12”>
[type = ‘text’] or [id = ‘abc12’]
input[type = ‘text’] or input[id = ‘abc12’]
Syntax:
[Link]([Link]("Expression"));

Advantages:
1. cssSelector is faster than xpath.
2. cssSelector expression is simple & easy to understand.
Disadvantages:
1. cssSelector can be applied only for attributes.
2. It cannot handle text.
3. It cannot handle dynamic data.
4. It can traverse only in unidirectional cannot
travel upwards in the DOM.
5. Traversing is possible only form parent to child.
8. xpath(String xpath)
1. Xpath represents XML Path (Extensible Path).
2. XML stands for Extensible Markup Language.
3. XPath is used to traverse through the HTML structure
& locate elements by attributes, texts, and parent
child hierarchy using different syntax formats.
4. Even though xpath is slower it is the strong locater.
5. There are Two Types of xpaths:
a. Absolute XPath
i. Starts with /  Search from root node
ii. Fragile → breaks when UI/logic changes
iii. Example: ./html/body/div[1]/input
b. Relative XPath
i. Starts with //  Search anywhere from the DOM
ii. Strong and Preferred in real-time.
iii. Example: //input[@id='username']

There are different types of Relative xpaths are available:


1. xpath by single attribute 8. xpath by index
2. xpath by text 9. svg tags xpath
3. xpath by contains
4. xpath by multiple attributes
5. xpath by axes-names
6. xpath by surroundings
7. xpath by normalize-space
8. xpath by starts-with
1. xpath by single attribute
It is used to identify web element using attribute
and value pair.
Syntax:
//tagname[@attributename = ‘attribute value’]
Example:
<input type="password" placeholder="Password"/>
//input[@type = ‘password]

2. xpath by text()
It is used to identify web element using visible
text on the web page.
We should make use of a method called text().
Syntax:
//tagname[text() = ‘visible text']
Example:
<ahref="[Link]/">Facebook</a>
//input[text() = ‘Facebook’]
3. xpath by contains()
It is used to identify web element using a method
called contains().
Here there are 2 approaches to follow,
3.1. xpath by contains() using attribute
Syntax:
//tagname[contains(@AN , ‘AV’)]
Example:
<input type="password" placeholder="Password"/>
//input[contains(@type , ‘password’)]

3.2. xpath by contains() using text


Syntax:
//tagname[contains(text() , ‘visible text')]
Example:
<ahref="[Link]/">Click Here To Apply</a>
//input[contains(text() , ‘Click He’)]
4. xpath by multiple attributes
It is used to identify web element using multiple
attributes using logical operator like AND & OR.
Syntax:
//tagname[@AN = ‘AV’ and @AN = ‘AV’]
//tagname[@AN = ‘AV’ or @AN = ‘AV’]
Example:
<input type="password" placeholder="Password"/>
//input[@type=‘password and @ placeholder=’Password’]
//input[@type=‘password or @ placeholder=’Password’]
4. xpath by axes
It is used to identify web element using axes names.
It is used when there no values used for the target
element while web page development.
There are multiple axes names available like,
1. parent 4. child
2. following-sibling 5. preceding-sibling
3. ancestor 6. descendant
Syntax:
//tagname[@AN = ‘AV’]/axes-name::tagname
Example:
<form>
<input type="text" placeholder="Username"/>
<input type="password" placeholder="Password"/>
<button>Login</button></form>

//input[@type=’password’]/following-sibling::button
5. xpath by surroundings
When the web element is developed using same
logic, xpath by surrounding can be used to
identify the web element uniquely.
It will be considered as dependent element and
independent element.
“/..”  is used to traverse back to the immediate
common parent.
Syntax:
//tagname1[@AN=‘AV’]/..//tagname2[@AN=‘AV’]

//tagname1[@AN=‘AV’] – independent element


/.. – traverse back
//tagname2[@AN=‘AV’] – dependent element

Rules to be followed:
1. Identify dependent element and independent
element.
2. Write xpath for independent element.
3. Traverse back to the immediate common
parent.
4. Write xpath for dependent element.
6. xpath using normalize-space
It is used to identify web element by ignoring
the extra spaces.

Syntax:
//tagname[normalize-space(@AN)=’AV’]
//tagname[normalize-space(text())=’text’]

7. xpath by index
It is used to identify web element which has index
values. Here indexing starts from 1.
It can be used as a supporting option when no other
xpath strategy is uniquly identifying the web element.

Syntax:
(//tagname[@AN = ‘AV’])[n]

8. xpath using starts-with()


It is used to identify web element uniquely with
the help of only the beginning part of the whole
data of the particular web element.

Syntax:
//tagname[starts-with(@AN,’AV’)]
//tagname[starts-with(text(),’text’)]
9. svg tags xpath
It is used to identify web element which are developed
using svg tag, SVG stands for Scalable Vector Graphics.
It is used to develop vector images, logos & etc.,

Syntax:
//*[local-name()=’svg’] or //*[name()=’svg’]

Advantages:
1. xpath is bidirectional.
2. It is strong and reliable.
3. Elements with only text can be identified.

Disadvantages:
1. It is slower than cssSelector.

WebElement
1. WebElement is an interface in Selenium.
2. It provides mechanism to interact with the web
elements that are present in the web page.
3. It has several inbuilt methods to interact with
web elements.
7. WebElement Methods
 WebElements is an interface in Selenium that
contains method to interact with web elements
on the web page.
 WebElement interface provide mechanism to
interact with the web elements on view port
area.
 There are 14+ inbuilt methods and 3 inherited
methods from SearchContext interface and
TakesScreenshot interface.
 Any element present on a web page is called as
Web Element. (button, textbox, link, image, etc.)
TakesScreenshot
It is an interface in Selenium which is used to take screen
shot of the current web page or web element.
It has only one abstract non-static method,
1. getScreenshotAs()
Here both web page and web element screenshot is
possible to take.

getScreenshotAs()
The purpose of this method is to take screen shot of
the current web page or web element.
It takes OutputType argument. They are,
1. FILE - File
2. BASE64 - String
3. BYTE - BYTE[]
Return Type of getScreenshotAs() is based on the
OutType argument that is passed.

1. getScreenshotAs([Link]);  File
2. getScreenshotAs(OutputType.BASE64);  String
3. getScreenshotAs([Link];  byte[]
SearchContext Interface
 It is the super-most interface in Selenium.
 It provides mechanism to locate or identify components
on the web page. [It only knows how to "find" things]
 It consist of 2 abstract non-static methods,
1. findElement(By by)
1. This method is used to identify / locate the first
matching web element.
2. It takes By type argument.
3. Return type is WebElement.
4. If the element is not located findElement(By)
will throw NoSuchElementException.
Syntax: [Link](By);

2. findElements(By by)
1. This method is used to identify multiple web
elements present in one go with same
characteristics inside the view port area.
2. It takes By type argument.
3. Return type is List<WebElement>.
4. If the element is not located findElements(By)
will return Empty List.
Syntax: [Link](By);
WebElement Method
There are 14+ in-built methods are there in
WebElement interface.
They are,
1. click() 5. getText() 12. isEnabled()
2. sendKey() 6. getTagName() 13. isSelected()
3. clear() 7. getAttribute(String name) 14. isDisplayed()
4. submit() 8. getCssValue(String propertyName)
9. getSize()
10. getLocation()
11. getRect()

1. click()
 click() is a method present in WebElement interface,
used to perform click operation on the web element.
 It is a no arguments method.
 Return type is void.
Ex: links, buttons, radio buttons

2. sendKeys()
 sendkeys() is a method present in WebElement
interface, used to enter String value in an element.
 It takes (character sequence) String type arguments
method.
 Return type is void.
Ex: text box,text area
3. clear()
 clear() is a method present in WebElement interface,
used to clear any value present in any element like
text field, text area and etc.,
 It is a no arguments method.
 Return type is void.
Ex: text box,text area

4. submit()
 submit() is also used to click on an element but
there are some rules should be followed while
working with submit().
 Rules to be followed:
o Element should have the attribute value pair
as type = “submit”
o HTML tag of the web element should be
present inside the <form> tag.
 When both the conditions satisfied submit() can
be used.
 It is a no arguments method.
 Return type is void.
5. getText()
 It is used to capture the visible text present in
the web element.
 It is a no arguments method.
 Return type is String.
 When there is no text present in the html source
code of an element, it returns an empty string.

6. getTagName()
 It is used to capture the tag name of the web element.
 It is a no arguments method.
 It returns tag name associated with the web element.
 Return type is String.

7. getAttribute(String attributeName)
 It is used to capture the attribute value of the
web element like label, id, class, name & etc.,
 It takes String type argument, from the inspection
page (DOM page).
 It returns the value associated with the attribute
name provided.
 Return type is String.
8. getCssValue(String cssPropertyName)
 It is used to capture the CSS properties of the
web element like color, font-size and etc.,
 It takes String type argument, from style section of
the inspection page (DOM page).
 It returns the value associated with the CSS property
given.
 Return type is String.

9. getSize()
 It is used to capture the Dimension (Height and
Width) of the web element.
 It is a no argument method.
 Return type is Dimension.
Dimension:
o It is a class in Selenium.
o It has 2 methods, getHeight() & getWidth().
o Return type of these methods is int.

10. getLocation()
 It is used to capture the Position(X & Y
coordinates) of the web element.
 It does not take any arguments.
 Return type is Point.
Point:
o It is a class in Selenium.
o It has 2 methods, getX() & getY().
o Return type of these methods is int.

11. getRect()
 It is used to capture the Dimension (Height &
Width) and Position (X & Y coordinates) of the
web element.
 It does not take any arguments.
 Return type is Rectangle.
Rectangle:
o It is a class in Selenium.
o It has 4 methods, getHeight(), getWidth(), getX()
& getY().
o Return type of these methods is int.

12. isDisplayed()
 It is used to checks whether the element is present
or not on the webpage.
 It does not take any arguments.
 If element is present on the webpage, it returns
true.
 If the element is not present on the webpage, it
returns false.
 Return type is boolean.

13. isSelected()
 It is used to checks whether the element is selected
or not on the webpage.
 It does not take any arguments.
 If element is selected on the webpage, it returns
true.
 If the element is not selected on the webpage, it
returns false.
 Return type is boolean.

14. isEnabled()
 It is used to checks whether the element is enabled
or not on the webpage.
 It does not take any arguments.
 If element is enabled on the webpage, it returns
true.
 If the element is disabled on the webpage, it
returns false.
 Return type is boolean.
8. Synchronization
 Synchronization is a process of matching 2 different
events according to requirement to maintain
seamless workflow.
 Application performance speed is different than the
automation tool speed. Usually, application loading
speed is slower when compared to automation tool
execution speed.
 Hence, test scripts fail as the element/page will not
be loaded while Selenium is trying to perform any
action.
 To handle this, Selenium provides different wait
statements to match the text script execution speed
according to the application loading speed.
 In automation, synchronization is considered as one
of the biggest challenges, hence waits are very
important in test scripts.

Different Ways to Handle Synchronization


1. Hard Wait
2. Implicit Wait
3. Explicit Wait
4. Fluent Wait
1. Hard Wait
 It is a Java wait statement, it will pause the execution
for the specified duration and resume.
 It is also known as Dead Wait, since it blindly waits for
declared amount of time without checking conditions.
 Using it frequently in test scripts increases overall
execution time.
Syntax: [Link](milliSeconds); 1000 milli sec = 1 sec
Application of Hard Wait:
1. For debugging purpose.
2. For small demo/part execution.
3. If there is any known/fixed wait time is required.
4. For learning purpose.

2. Implicit Wait
 It is a Selenium wait command.
 It saves execution time by waiting until the element is
fully loaded & visible on the web page.
 Implicit wait Works for:
findElement() & findElements()
 Default polling period: 500 milliseconds (0.5s) →
keeps checking for the element every 500
milliseconds until the declared time is over.
 If element is not found and time is over:
o findElement() → throws NoSuchElementException
o findElements() → returns an empty List<>
 Usually applied once at the beginning of the test (after
launching browser, before URL load) & works only until
element identification.
 Should be declared using method implicitlyWait(), it
takes Duration type argument from [Link] package.

Syntax:
[Link]().timeouts().implicitlyWait([Link](sec));
3. Explicit Wait
 It is also a Selenium wait command, works based on
given condition, it stops waiting as soon as condition is
satisfied and leaves the driver control to next line.
 Default polling time: 500 milliseconds (0.5s) → keeps
checking for the condition every 500 milliseconds until
the declared time is over.
 If condition not met → throws TimeoutExcep on.
 Implementation:
 Creating object of WebDriverWait class.
 Passing conditions using ExpectedConditions class.

 Advantage: Synchronizes any element/page with


conditions, where implicit wait works until the web
element is available on the web page.
Syntax:
WebElement element = [Link]([Link](“a1”));
Duration duration = [Link](10);
WebDriverWait wait = new WebDriverWait(driver, duration);
[Link]([Link](element));
[Link]();

4. Fluent Wait
 It’s a Selenium wait command works similar to
Explicit Wait (based on conditions).
 The only difference between Explicit Wait and Fluent
Wait allows to customize the polling time instead of
default polling period of 500ms.
 Implemented by creating object of FluentWait class &
Polling time can be customized using pollingEvery().
 It is used only when changing polling interval is
necessary.
 It is not used very often in real time projects.
9. TakesScreenshot
It is an interface in Selenium which is used to take screen
shot of the current web page or web element.
It has only one abstract non-static method,
[Link]()
Here both web page and web element screenshot is
possible to take.

getScreenshotAs()
The purpose of this method is to take screen shot of
the current web page or web element.
It takes OutputType argument. They are,
1. FILE - File
2. BASE64 - String
3. BYTE - BYTE[]
Return Type of getScreenshotAs() is based on the
OutType argument that is passed.

1. getScreenshotAs([Link]);  File
2. getScreenshotAs(OutputType.BASE64);  String
3. getScreenshotAs([Link];  byte[]
10. Select Class
Drop-down / List Box is the GUI menu that allows
users to choose one value or multiple values from a
list of options which is wrapped in the web page.
There are 2 types of drop downs available,
1. Single select drop down 2. Multi select drop down

Drop downs are developed using <select> tag and <options> tag.

How to we handle drop downs using Selenium?


In Selenium, there is a class called Select, which is
specifically used to interact with drop downs.
Select is a concrete class in Selenium which is available
in [Link] package.
/**create object for Select class & pass the WebElement
reference into the constructor.**/
Select sc = new Select(WebElement element);

There are 3 ways to select options from the drop down.


Use the Select class reference variable and select
options with the help of index, value & visible text.

1. selectByIndex(int index)
It is used to select options from dropdown by using
index value. Here indexing starts from '0'.
It takes integer type argument (index).
Return Type is void.
2. selectByValue(String Value)
It is used to select options from dropdown based on
value present in the DOM page.
The value attribute present inside option tag will be
used as argument.
It takes String as an argument (attributeValue).
Return Type is void.

3. selectByVisibleText(String Text)
It is used to select options from dropdown based on
visible text present between > & < symbol of <option>
tag will be used as argument here.
It takes String as an argument (text present in <option>).
Return Type is void.
There are 4 ways to deselect the options from drop
down.
1. deselectByIndex()
2. deselectByValue()
3. deselectByVisibleText()
4. deselectAll()

De-select methods will work only for multi select


dropdown. It will not work for single select dropdown.
In-order to deselect options the tag name should
contain multiple attribute.
<select multiple>…</select>

1. deselectByIndex(int index)
 It is used to deselect options from dropdown
using index value. Here indexing starts from '0'.
 It takes integer as an argument (index).
 Return Type is void
2. deselectByValue(String Value)
 It is used to deselect options from dropdown based
on value present in the DOM page.
 The value attribute present inside option tag will be
used as argument.
 It takes String as an argument (attributeValue).
 Return Type is void.

3. deselectByVisibleText(String Text)
 It is used to select options from dropdown based on
visible text present between > & < symbol of
<option> tag will be used as argument here.
 It takes String as an argument
(text present in <option>).
 Return Type is void.
4. deselectAll()
 It is used to deselect all the selected options
from dropdown. It does not take any arguments.
 Return Type is void.

Note:
If deselect methods are used on single select
dropdown, it will throw UnsupportedOperationException
If Select class operation is used, when there is no
select tag present in DOM, Selenium will throw
UnexpectedTagNameException

Few more methods available in Select class are,


1. getFirstSelectedOption()
2. getAllSelectedOption()
3. getOptions()
4. isMultiple()

1. getFirstSelectedOption()
 It is used to capture the first option from the selected
options in the dropdown according to the DOM order.
 It is a no argument method.
 Return Type is WebElement.
2. getAllSelectedOptions()
 It is used to capture all the selected option from
the dropdown.
 It is a no argument method.
 Return Type is List<WebElement>.

3. getOptions()
 It is used to capture all the option inside the
dropdown menu.
 It is a no argument method.
 Return Type is List<WebElement>.

4. isMultiple()
 It is used to verify whether the dropdown/list
box present is a single select dropdown or multi
select dropdown.
 It is a no argument method.
 Return Type is boolean.
11. Actions Class
Actions is a class present in Selenium used to handle
mouse and keyboard operations like right click, double
click, mouse hover, click & hold, drag and drop etc.,

How to we handle drop downs using Selenium?


Actions is a class present in Selenium under
[Link] package.
Actions class has non-static methods, so object creation
is required to use the methods present.
WebDriver reference (driver) should be passed into the
constructor while creating object. So that Selenium can
instruct methods of Actions class to perform actions on
any web element.

/**create object for Actions class and pass the


WebDriver reference into the constructor**/
Actions act = new Actions(WebDriver driver);

By using Actions class, we can perform tasks/actions


like,
1. Right Click 4. Mouse Hover
2. Double Click 5. Scrolling
3. Click & Hold 6. Drag & Drop
1. Right Click:

1. contextClick()
This method is used to perform right click on the web
page.
It does not take any arguments.

Syntax:
Actions act = new Actions(driver);
[Link]().perform();

2. contextClick(WebElement element)
This method is used to perform right click operation on
the web element.
It takes WebElement as argument.

Syntax:
WebElement element = [Link]([Link](“abc”));
Actions act = new Actions(driver);
[Link](element).perform();
2. Double Click

1. doubleClick()
This method is used to perform double click on the web
page.
It does not take any arguments.

Syntax:
Actions act = new Actions(driver);
[Link]().perform();

2. doubleClick(WebElement element)
This method is used to perform double click operation on
the web element.
It takes WebElement as argument.

Syntax:
WebElement element = [Link]([Link](“abc”));
Actions act = new Actions(driver);
[Link](element).perform();
3. Click & Hold

1. clickAndHold()
This method is used to perform click and hold on the web
page.
It does not take any arguments.

Syntax:
Actions act = new Actions(driver);
[Link]().perform();

2. clickAndHold(WebElement element)
This method is used to perform click and hold operation
on the web element.
It takes WebElement as argument.

Syntax:
WebElement element = [Link]([Link](“abc”));
Actions act = new Actions(driver);
[Link](element).perform();
4. Mouse Hover

1. moveToElement(WebElement element)
This method is used to perform mouse hover operation
on the web element.
It takes WebElement as argument.

Syntax:
WebElement element = [Link]([Link](“abc”));
Actions act = new Actions(driver);
[Link](element).perform();

2. moveByOffset(int X, int Y)
This method is used to perform mouse hover operation
on the web element based on X & Y coordinates.
It takes 2 int type as arguments (int X and int Y).

Syntax:
Actions act = new Actions(driver);
[Link](int X, int Y).perform();
5. Scrolling

1. scrollToElement(WebElement element)
It will perform scrolling operation on the webpage until the
web element appears into the view port area.
It takes WebElement element as arguments.
It will scroll both horizontally and vertically.

Syntax:
Actions act = new Actions(driver);
[Link](webElementRef).perform();

2. scrollByAmount(int X, int Y)
It will perform scrolling operation based on X & Y position. It
will scroll both horizontally and vertically.
It takes int deltaX & int deltaY as arguments.
If we want to scroll backward, pass negative coordinates.

Syntax:
Actions act = new Actions(driver);
[Link](int deltaX, int deltaY).perform();
6. Drag and Drop

1. dragAndDrop(WebElement src, WebElement trg)


This method is used to perform drag and drop operation
of a source web element into a target location.
Here both source and target will be WebElements.
It takes 2 web elements as argument.

Syntax:
WebElement src = [Link]([Link](“abc”));
WebElement trg = [Link]([Link](“xyz”));
Actions act = new Actions(driver);
[Link](src,trg).perform();

2. dragAndDropBy(WebElement src, int X, int Y)


This method is used to perform drag and drop operation
of a source web element into a target location based on
the X & Y coordinates.
It takes 3 arguments (WebElement src, int X and int Y).

Syntax:
Actions act = new Actions(driver);
[Link](WebElement src, int X, int Y).perform();
12. iFrames
Frames are Embedded Web Pages which are developed
using HTML tag called <frame></frame>.
What is Embedded Web Page?
A web page inside another web page is called as
Embedded Web Page.

Purpose of using iFrames in web application


1. To post advertisements on the web page.
2. To develop commonly used features.
3. To merge common code in one server.

There are different types of iFrames,

Single Frame Multiple Frame Nested Frame

How to handle iFrame using Selenium?


Frames cannot identified the just by looking at the web
page, but when we do right click on the web page, we
get an option that is “View Frame Source”, using this we
can identify frame is used or not.
Also when we inspect <iframe></iframe> tag will be
visible in the DOM page using this technique also we
can identify frame is used or not.

If we need to perform any action on the frame, we


need to transfer the driver control into the frame.
To transfer the control there is a method called
frame() inside TargetLocator interface.

Syntax:
1. Using index -> indexing starts form '0'
[Link]().frame(int index);
2. Using name or id
[Link]().frame(String nameorId);
3. Using Web Element / Frame Element
[Link]().frame(WebElement FrameElement);
To switch back the driver from frame to main web
page:
1. Using defaultContent() we can transfer the driver
control directly to main web page out of all frames,
Syntax:
[Link]().defaultContent();
2. Using parentFrame() we can transfer the driver
control to immediate parent,
Syntax:
[Link]().parentFrame();

Note:
When the identifier is incorrect, driver will through
NoSuchFrameException.
All the methods related to frames will return WebDriver
interface. Which allows Selenium to perform WebDriver
actions inside the frame.
13. Popups
Pop-ups are some GUIs that appears on the web page,
while end user performs some action on the web page.
In Selenium, pop-ups can be handled or avoided based
on the type and nature of the pop-up.

Purpose of using Pop-ups in web application


1. To grab attention of end users.
2. To give information to end users.
3. To collect information from end users.

Types of Pop-ups
1. JavaScript Popup
2. Hidden Division Popup
3. File Upload Popup
4. File Download Popup
5. Notification Popup
6. Authentication Popup
7. Child Window Popup
1. JavaScript Popup
JavaScript popups are developed using JavaScript
Language, which should be handled.
We cannot avoid these popups because web page will be
frozen until it is handled.
There different types of JavaScript Popups available,

Characteristics of JavaScript Popup


1. We cannot inspect JavaScript Popup.
2. We cannot move JavaScript Popup.
3. Webpage will be frozen until the popup is handled.
4. It always appears on the top center and right below
the address bar.
How to handle JavaScript Popup?
There is a method called alert() present in TargetLocator
Interface. It is used to handle JavaScript Popups.
Return Type of alert() is Alert.
Alert:
Alert is an interface in Selenium.
There are 4 methods available in Alert Interface,
which can be used to perform actions ->
4. accept() 2. dismiss() 3. sendKeys() 4. getText().
Return Type accept(), dismiss(), sendKeys() is void and
getText() is String.

Syntax:
Alert jsPopup = [Link]().alert();
[Link](); //other method can also be called
using the same reference variable.
Note:
In “alert popup” both accept() and dismiss() will click on
OK button, but not in confirmation popup and prompt
popup.
Exceptions in JavaScript popup:
Whenever we try to perform any action on the webpage
without handling the JavaScript Popup, we will get
UnhandledAlertException.
If the alert popup is not present on the web page (or) if
the Automation Engineer tries to handle the alert popup
before it appears on the web page, Selenium will
through NoAlertPresentException.

2. Hidden Division Pop up


These are pop ups which always overlay on the web
page which are created using HTML tree structure.
In general, any pop-up which can be inspected is
considered a Hidden Division Popup.

Characteristics of Hidden Division Popup


1. We can inspect Hidden Division pop up.
2. We cannot move Hidden Division pop up.
How to handle Hidden Division Popup?
Hidden Division Popups can be handle using the
regular approach.
Directly handle using findElement(By)/findElements(By),
WebDriver & WebElement methods to interact with
elements.

Note:
Hidden Division Pop up is not a browser level pop
up/alert, so no need to use alert() from TargetLocator.
Generally, it is used for Calendars, Date Picker, Filter
modals, and etc.,
We will use findElement(By), findElements(By) for-loop,
try-catch block and WebElement methods like click().

3. File Upload Pop up


These pop ups will appear when there is a need to
upload any file from the local storage to the web page.
Characteristics of File Upload popup:
1. We cannot inspect File Upload popup.
2. We can move File Upload popup.
3. These pop ups will contain open and close buttons.
How to handle File Upload Popup?
Step 1: Identify tag & attribute  <input type= "file">
Step 2: Use sendKeys() to pass the 'file path' into it.
(OR)
Robot class can be used to handle File Upload Popup.

4. File Download Popup


By default Selenium will handle File Download Popup.

5. Notification Popup
It is a browser level pop up that gives some information
to the end-user and may ask for some permissions if the
application needs.
Characteristics of Notification Popup:
1. We cannot inspect Notification Popup.
2. We cannot move Notification Popup.
3. These pop-ups contains Allow & Block button.

How to handle Notification Popup?


It can be disabled by changing the browser settings with
the help of a ChromeOptions, FirefoxOptions, or
EdgeOptions classes available in Selenium.
Robot class can also be used to handle Notification Popup.
Step1: Create object for ChromeOptions class.
Step 2: Call addArguments(String chromiumCommand)
and pass the Chromium Command (available in
Chromium Command websites).
Step 3: Pass the reference variable into the constructor
of browser specific class while launching browser.

Few Chromium Commands are,


1. --disable-notifications
2. --start-fullscreen
3. --start-maximized
4. --incognito
5. --headless

6. Authentication Popup
It appears, whenever the web page is requesting for
verification.
Without handling authentication popup, we cannot login
to application.
Selenium does not have inbuilt method to handle these
type of popup but there are other ways to work with
these kind of popups.
Robot Class or AutoIT can be used to handle these
popups.
Characteristics of Authentication Popup:
1. We cannot inspect these pop ups.
2. We cannot move these pop ups.
3. These pop-ups contains username, password,
login button and cancel button.

How to handle Authentication Popup?


We can avoid the popup by pass the username and
password along with the url in get(String url).

Syntax:
[Link]
url: [Link]
username: admin password: admin

[Link](“[Link]

7. Child Window Popup


It appears, whenever the end user perform and click
action on the web page.
A new window gets opened as a result of the click, here
the first page is called as parent window and the new
window that popped is called as child window.
It will have all the features that parent window contains.
Characteristics of Child Window Popup:
We can inspect Child Window pop up.
We can move Child Window pop ups.
These pop-ups contains all the features as same as a
parent window.

How to handle Child Window Popup?


In order to handle Child Window Popup we need to
transfer the driver from parent window child window
using window() present in TragetLocator interface.
Capture the session IDs using getWindowHandle() &
getWindowHandles() and pass it as argument into the
window().

Syntax:
[Link]().window(windowID);
14. JavaScriptExecutor
JavaScriptExecutor is an interface in Selenium.
It provides mechanism to write the JavaScript code inside
Selenium.
It has 2 abstract non-static methods,
1. executeScript(String script, Object... args)
2. executeAsyncScript(String script, Object... args)

Why JavaScriptExecutor is used?


When, WebDriver & Actions class fails, JavaScriptExecutor
can be used to handle the situation gracefully.

Syntax:

Using JavaScriptExecutor, we can perform window


scrolling, perform action on hidden elements and
disabled elements.
3 – Global objects available in JavaScript
1. window
2. document
3. arguments[0]

1. scrolling using JavaScriptExecutor


1. [Link](int X, int Y)
2. [Link](int X, int Y)

2. perform action on hidden elements


arguments[0].click()

3. perform action on disabled elements


arguments[0].value=’String Value’
15. Data Driven testing [DDT]
Testing the application with multiple sets of data which
are stored in an external resource file is called Data
Driven Testing.
What is External Resource File?
A file that stores configurations, test data, reusable
information outside the test script.
Example: Properties File, Excel File.
Properties File
It is a java configuration file used to store data.
By default, properties file will accept data only in String
format.
In order to store data into properties file we need to
follow some set of rules.
Rules to be followed
1. Data should be stored in key & value format.
2. key & value should be separated using ':',' ', '='.
3. File must be saved with .properties extension.

Read data from Properties file:


Advantages of storing data in Properties file
1. It is faster compared to other external files.
2. Light weight and easy to store data.
3. Consumes very less memory.
Disadvantages of storing data in Properties file
1. Every value should have unique key.
2. Need to remember all the keys.
3. Only one key value pair is allowed per line.

Excel File
Excel file is a workbook / spreadsheet / table that contains
rows & columns, also it stores data in the same format.
Excel workbook stores data in well-organized manner.
Because of this nature, it is easy to store and identify
data present inside the excel workbook.
Excel is not a web application but is a desktop
application (Standalone Application).
Selenium cannot directly automate excel workbook, it
requires a 3rd party tool to access the data stored inside.

The name of the 3rd party tool is called 'Apache Poi'.


How to Store data in Excel File
1. Open the excel workbook.
2. Enter data into cell according to the requirement.
3. Save the workbook (with extension .xlsx / .xls).
4. Close the Workbook.

Read data from Excel File


1. Navigate to maven repository and search for
apache poi.
2. Take version 4.1.2 from [Link] » poi-scratchpad
and [Link] » poi-ooxml-schemas
3. Copy paste both the dependency code in to
[Link] file. (remove only ‘-schemas’)
4. Save the [Link] file
5. Follow the below syntax
Syntax to Read data from Excel file:
Advantages of storing data in Excel File
1. No need to store data in key value pair.
2. Data can be stored in rows and columns format.
3. Can store large amount of data in single file.
Disadvantages of storing data in Excel File
1. Slower than properties file.

Advantages of Data Driven Testing


1. DDT separates test data from test script.
2. Same data can be used in multiple test scripts.
3. Increased test coverage.
4. Modification of test data becomes easier
5. Maintenance of test data becomes easier
6. Test data can be prepared even before scripting.
7. Reduces time and complexity.

Use these two approaches:


1. Use Property File for common data (URL, browser,
etc.)
2. Use Excel for large test data (multiple login
credentials, inputs for forms, etc.)

As per rule of automation test data should not be hardcoded


16. Page Object Model [POM]
POM (Page Object Model) is a Java design pattern
preferred by Google to store web elements at one place
to avoid hardcoding of web elements in Test script.
Using POM technique web elements can be stored
directly in java classes and can be retrieved in test scripts
during execution.
Rules to be followed while creating POM class
1. No of POM Classes = No of Web pages.
2. No of variables = No of web elements.
3. Declare web elements using @FindBy.
4. All the web elements should be declared private.
5. Initialize with PageFactory class.
6. Access web elements using getters.

@FindBy is used to locate the web element using any


locator strategy.
Frequent changes in the UI will impact execution and
leads to significant maintenance and rework of existing
test scripts.
To avoid that and to handle web elements efficiently,
POM class is used.
All the POM classes will be stored in src/main/java
under a package called objectRepository.

As per rule of automation web elements should not be hardcoded


Advantages of using POM class:
1. Modification of web element becomes easier.
2. Maintenance of web element becomes easier.
3. Web element can be reused.
4. Web elements can be shared across the team.
6. Code Optimization is improved.
7. Code readability is improved.
8. POM can avoid 'StaleElementReferenceException'.

StaleElementReferenceException occurs when Selenium


tries to interact with an old web element address that is
no longer present in the current page's DOM.

PageFactory is an in-built class in Selenium used to initialize


all @FindBy annotated web elements during object
creation.
initElements() is used to set up web elements and delay the
searching of web elements (lazy initialization).
If it is not used, @FindBy will not work and web element
will return null. As a result, NullPointerException will occur.
17. TestNG [Test Next Generation]
TestNG means Test Next Generation. It is unit testing tool
/ framework / library which supports Java.
It is used by developers to perform unit testing.
Automation Test Engineers use TestNG to develop and
maintain test scripts in a more optimized way and also to
perform,
1. Batch Execution
2. Parallel Execution
3. Group Execution
4. Report Generation
Rules to be followed while working with TestNG:
1. Use @Test annotation instead of main().
2. Use [Link]() instead of [Link]().

@Test
It is an annotation present in [Link]
one of the important annotations in TestNG.
It will drive the test script like a main().
Multiple @Test annotation can be used in a single
class.
All the annotations in TestNG should be declared as
public and return void.
If multiple @Test annotations are used in a single
class, they will be executed according to the ASCII
values of the method names.
Execution order can be modified using Helper Attribute.

Helper Attributes / Annotation Attributes:


Helper Attribute helps in execution perspective by
providing some in-built attributes.
1. Priority
2. Invocation Count
3. Thread Pool Size
4. Enabled
5. Depends On Method
1. Priority
It is used to decide the execution order of each test case.
By default, value of priority is '0' for all the test cases.
If priority is not provided for test cases, TestNG executes
based on alphabetical order / ASCII value order.

Lower the value of priority, 1st comes will execute 1st.


priority value can be also negative. Syntax: (priority = n)
2. Invocation Count
It is used to execute the same test case multiple times.
By default, value of invocation count is '1'.
Values must be positive because if the value is
negative or 0 (value<=0) test case will not execute.
(invocationCount = n)

3. Thread Pool Size


It is used to execute same test case multiple times
simultaneously.
By default, value of Thread Pool Size is '0' for all test
cases.
Value should be greater than or equal to invocation
Count.
Declaration of invocation Count is mandatory in
order to use the Thread Pool Size.
(invocationCount = n, threadPoolSize = n)

4. Enabled
It is used to ignore the test cases from execution.
By default, value of enabled is 'true'.
In order to skip the execution of particular test case
declare enabled as 'false'.

Note:
There are 2 approaches to skip the execution of a
particular test case. They are,
1. enabled = false
2. invocationCount = 0 (or) -1 (or) -2...
5. Depends on Methods
Whenever there is a dependency between test cases
(methods), we go for depends On Methods.
If the provider test case is failed / skipped, dependent
test case will not execute.
Dependent test case will execute only when the provider
test case executes.
(dependsOnMethods = “ProviderMethodName”)
If a test case depends on multiple provider test cases, we
can use the following syntax,
(dependsOnMethods ={“ ”,” ”,” ”,…})
Automation Test Engineers use TestNG for,
1. Batch Execution
2. Parallel Execution
3. Group Execution
4. Report Generation

1. Batch Execution
Executing multiple TestNG classes in one shot is called
Batch Execution.
(or)
Executing all TestNG classes via suite file is called as
Batch Execution.
2. Parallel Execution
Executing multiple TestNG Classes simultaneously is
called as Parallel Execution.
While refactoring (generating [Link]) file ‘classes’
under Parallel mode menu.
We can run parallel suite in,
<test parallel = "methods"> -> methods level
<test parallel = "classes"> -> classes level
<test parallel = "tests"> -> tests level

3. Group Execution
In TestNG Executing specific group of test cases which
created while scripting with group attribute is called as
Group Execution.
Categorizing the test cases into groups (eg: smoke,
regression, system, delete, create and etc.,) using the
helper attribute called ‘groups’.

Syntax: @Test (group = “GroupName”)

Here, we can run only selected (i.e., grouped) test cases.


Grouping test cases should be done at scripting stage.
Why group execution?
Group execution Saves time as it execute runs only
relevant test cases in one click.

Advantages:
Maintaining large scenarios becomes easier.
Less changes required in code.

Application:
Single test case can be in multiple groups.
dependsOnMethod plays a major role in multiple classes.
Group filtering is also possible.
Able to run different groups simultaneously.
4. Report Generation
TestNG automatically generates report in readable
format after each execution.
There are 2 main types of reports available in testNG.
They are,
1. [Link]
2. [Link]
There will be no backup for reports generated in testNG.
As it is a temporary storage point/memory place, we
should manually store the file in an external folder every
time after execution.
Project  test-output  [Link], [Link]

TestNG Assertion
Assertions are testNG class used to verify certain check
points in the test case. It is one of the key features that is
available in TestNG.
Assertion helps in analyzing the test case, whether it the
test case gets pass (or) fail.
Assertion has the capability to fail the test case if the
expected result and actual result is not matching.
The order of passing arguments in any assertion
methods is always actualValue, expectedValue.
Types of Assertions
1. Hard Assert
If there is any failure, Hard Assert will terminate the
execution and fails the test case.
All the methods present in Hard Assert are static.
2. Soft Assert
If there is any failure, it will not terminate the execution.
It collects all the failures and gives us a report in the end.
All methods present in Soft Assert are non-static.
18. Introduction to Maven
Maven is a project management tool.
It is also called as Build management Tool, Build testing
Tool and Build Dependency Tool.
Maven is majorly used for used for build creation, build
testing and build deployment.
Automation Test Engineer use Maven for Build Testing
and Dependency handling.
Multiple Build Testing Tools available in the market:
1. Gradle 2. Ant
3. NAnt 4. Maven
5. Cake and etc.,
Why Maven is preferred?
1. Handles dependencies automatically
2. Provides In-built folder structure.
3. Checks for compilation and integration issues
between source codes.
4. It provides quick project setup.
5. Maven uses simple commands to run script
and suite files.
There are 2 types of software in Maven
1. Maven Eclipse Plugin
2. Maven cmd line Plugin

1. Maven Eclipse Plugin:


It is an inbuilt plugin in eclipse. It helps to create Maven
project and provides folder structure to support
Framework development.
To create maven Project Group Id & Artifact Id are
mandatory,
Group id: Organization Name
Artifact Id: Project Name

[Link]
It is called as Project Object Model.
It is also called as Project Configuration file.
It is the heart of any maven project.
It is created only once during project creation and if the
[Link] is corrupted, then the entire project should be
discarded and should create a new project.
The components of [Link] are dependencies and
Plugins.
Dependencies in Maven
Dependency is an advance feature in maven which is
used to get all the required .jar files from the Global
repository ([Link] to Local repository
(C://user/name/.m2).
Maven configures all jars to project automatically after
storing the dependencies in [Link] file.

2. Maven Cmd Line Plugin:


Using Maven Cmd Line Plugin we can run the maven
project without launching eclipse.
Maven must be downloaded and installed into the local
system and need to setup the environment variables.
All the test scripts should be suffixed with 'Test' and
should be stored in src/test/java folder.
How to install Maven
1. Download Apache Maven Binary zip archive of version
'apache-maven-3.9.11- [Link]' from the link
[Link]
2. Extract the zip file and store.
3. Open the stored file navigate to bin folder and copy
the path. (C:\Users\User\apache-maven-3.9.11\bin)
4. Open Environment Variables by searching 'Edit the
system environment variables' in settings.
5. In user variable section, click on New button & provide
variable name as M2_HOME or MAVEN_HOME &
paste the path without '\bin'.
6. In system variable section, click on Path. New window
will appear, Click on New button and paste the full
path.
7. Click OK -> OK -> OK.

Once the setup is done, Open command prompt and


verify installation version. In cmd Line,
Type 'mvn -version' and press enter to check Maven
installation status & version.
Type 'java -version' and press enter to check Java
installation status & version.

How to install Java (if not insatlled)


1. Download Java from
[Link]
2. Download appropriate OS and version. Install the
software.
3. Open the installed folder navigate to bin folder and
copy the path.
4. Open Environment Variables by searching 'Edit the
system environment variables' in settings.
5. In user variable section, click on New button and
provide variable name as JAVA_HOME and paste the
path without '\bin'.
6. In system variable section, click on Path. New window
will appear, Click on New button and paste the full
path.
7. Click OK -> OK -> OK.

Once both are installed checked via cmd line, System is


ready to Process Maven Commands.

To execute the test script in command line:


1. Go to the current project location where [Link] file
is present in your local system & copy the project path.
2. Open cmd line and enter 'cd ProjectFilePath'.
3. Execute the maven life cycle commands in cmd line
and verify the execution status.

Basic Maven Commands:


1. mvn validate -> checks and downloads all the
necessary jars file according to the dependencies
added.
2. mvn compile -> checks for any compilation issues in the
framework.
3. mvn test -> identify all the test classes whose class
name end with "test" and executes them.
4. mvn clean -> It is a maven command used to clean all
the old reports.

These are called as Maven Life Cycle or Build Life Cycle of


Maven project.

Advantages of MAVEN
1. Handles .jar files gracefully with the help of maven
dependencies.
2. Create quick project setup for new engineers.
3. Provides simple framework folder structure.
4. Test script can be executed directly in command Line
without even launching Eclipse.
5. Best suit for agile Projects.
19. Introduction to GitHub
GitHub is a decentralized cloud based storage space.
It is used to store and access source code from anywhere over
the internet.
GitHub is also called as version control tool / source code
management tool / configuration management tool.
It allows multiple users work on same project without
overlapping each other.

GitHub is commonly used in Software Development


1. Developers use gitHub to maintain source code.
2. Devops Engineers use gitHub to maintain Builds.
3. Automation Test Engineers use gitHub to maintain their
complete framework.
4. Manual Test Engineers use gitHub to maintain manual test
cases.

Advantages
1. We can access the repository from anywhere with the help
of internet.
2. Source code / framework can be shared across the team
easily.
3. There will be no maintenance required, as it is a cloud
based storage place.
4. Pay rent and lease the servers, no need to buy and setup
any physical server.
20. Introduction to Jenkins
Jenkins is a CI/CD Tool used by Developers, DevOps
and Automation Testers.
CI ---> Continuous Integration
CD --> Continuous Development / Continuous
Deployment / Continuous Delivery
It is basically used by Devops Engineers to monitor
build in GitHub.
Jenkins is best fit for agile methodology as it needs
frequent build release.
Jenkins automates and streamlines the testing
process to make sure it gives faster execution and
feedback.
Basically Jenkins can automate:
1. Process of build creation - Continuous Development.
2. Process of installing the build into the testing
environment - Continuous Deployment.
3. Process of checking the integration issues between old
feature and new features - Continuous Integration.
4. Process of delivering the tested build to the production
environment - Continuous Delivery.
Why Jenkins is required in Automation?
1. Continuous Integration: Continuous execution of the
selenium test scripts in testing environment to check
for integration issues.
2. Continuous Integration means checking the integration
issues between the old build and new feature by
executing the old framework.
3. If the test scripts get failed, then we will get to know
the impact of new feature on the old build. hence we
can analyze the failure, debug the failed test scripts,
I. If the issue is occurring in the test script, fix and
update the framework & re-run the framework.
II. If the issue is occurring in product, log and rise the
defect.
21. Types of frameworks
Framework is a set of rules/guideline used to develop
the project and reusable components.
(or)
Framework is a collection of reusable components that
makes automation development, execution,
maintenance and modification easier.
(or)
Framework is a set of rules and instruction followed by
every organization to make Automation Test Engineer
life easy.

Types of Framework:
Test Driven Development -TDD:
Developing the framework based on test cases is called
Test Driven Development.
Here test scripts are written by referring the test cases,
so Test cases are mandatory.
@Test is the driving factor in TDD framework.
TestNG can be used for any TDD based framework.
These Frameworks are easy to develop and maintain.
1. Data Driven Framework:
Reading the test data form any external resource file like
property file / excel file /xml file / database and using
data provider to read the data.
This type of framework is called as Data Driven
Framework.
2. Modular Driven Framework
Whenever the project is very huge and consist of lots of
modules, maintaining all the test scripts and test data in
one place becomes very difficult, so module wise
framework development is followed.
For example POM classes are stored as module wise. This
is called as Modular Driven Framework.
3. Method Driven Framework
Creating generic/reusable methods and storing it as a
library, then calling them into the test script whenever
required. This kind of test script development is called as
Method Driven Framework.
Here all the reusable methods / reusable logics and
reusable syntaxes stored separately and used in script.
Whenever there are lot of repeated methods involved in
test script development, we go for Method Driven
Framework.
4. Keyword Driven Framework
Using the user-friendly keywords for all the WebDriver
actions is called as Keyword Driven Framework.
Whenever manual test engineers are involved in
development of automation test script, we go for
Keyword Driven Framework.
Here we do not need much coding knowledge to develop
the test script.
5. Hybrid Framework
Combination of two or more above discussed frameworks
is called as Hybrid framework.
Some applications will have huge data and more number
modules that requires multiple stack. Here can combine
two or more framework types to develop new framework.
Such framework is called as Hybrid Framework.

Behavior Driven Development - BDD


Test Scenarios are mandatory, anybody who has
application knowledge can write scenario.
@Given, @When and @Then are used in test script
development.
Cucumber library is used in BDD development approach.
Given, when, Then, And are the Gherkins language
keywords which helps to develop the script.
In Cucumber all Gherkins keywords will be annotations
Given => Pre conditions.
When => actions.
Then => post conditions.
And => break down the sentence or giving continuation.

Cucumber framework consists of 3 parts:


1. Feature file - Scenarios are written in Gherkins
Language.
2. Step Definition - every step in feature file will be
mapped to program.
3. Runner Class - Execution class to run the script.

Advantages:
1. BDD makes use of layman language hence it's easy to
understand.
2. BDD essentially concentrates more on required
features hence development and testing of required
features will be faster.
3. BDD helps in easy feature modifications.
4. Preferable for short term projects.
Disadvantage:
1. BDD requires high communication and collaboration
amongst team.
2. More Documentation.
3. Not suited for Long Term Projects.

Advantages of Framework:
1. Test script development becomes faster and easier.
2. Modification and maintenance of data becomes easier.
3. Modification & maintenance of web element becomes
easier.
4. Framework provides flexibility to achieve cross browser
testing, distributed environment testing, smoke testing,
regression testing, regional regression testing.
5. Framework provide accurate execution report for every
execution.
6. Framework provides generic reusable components.
7. Test script can be optimized and re-used for every new
build.

Disadvantages of Framework:
1. Initial development phase cost and time is high.
2. Should be good in programming.

You might also like