Selinium Full Notes
Selinium Full Notes
Sachin M H ,
INTRODUCTION
WHAT IS SELENIUM?
It is an open source tool which is used to validate your web application on any browser across all the
platforms.
Sachin M H
WHAT ARE THE ADVANTAGES OF SELENIUM?
❖ It is open source tool.
❖ Supports Multi Programming language like-JAVA, C#, PHYTON, RUBBY, PERAL,
JAVASCRIPT, PHP, HASKELL.
❖ Supports Multi browser -SAFARI, CHROME, EDGE, IE, FIREFOX, OPERA.
❖ Multi OS support-
o For web application like-WINDOWS, LINUX, MAC OS, UNIUX.
o For web mobile like-ANDROID, IOs.
Sachin M H
GENERIC SELINUM ARCHITECTURE
-It is language specific selenium libraries which contains all the functionalities of the tools by
obelizing the syntax of the compatible language.
• Client= user selected programming language.
• Bindings = selenium inbuilt functions available with respect to the selected programming language.
• Here we know java – so we will have java selenium rich libraries available as tool to perform
different actions on the web application which is under testing.
• Here client bindings are available in .jar format (jar means java arched).
• Example Java selenium (here we accessing selenium libraries w.r.t java syntax Semitics).
Sachin M H
JASON WIRE PROTOCOL
• Json can be abbreviated as JAVA SCRIPT OBJECT NOTATION.
• Its way of text representation of the data (paring), which in turn relatively easy to read and write for
the user and as well as for the s/w.
• Here text-based representation is nothing but key and value pair.
• EXAMPLE- {
COMPUTERS -DELL
MOBILE - REDMI
}
▪ This give the seamless comfort for the structure data to exchange it over the network typically
between Server and Web application.
DRIVER EXECUTABLE
▪ It is nothing but the executable s/w of the particular browser.
▪ It will act like a many server to trigger the actual browser in the local computer.
▪ It is always available in an executable format (.exe).
▪ It will help us to communicate the request to the specific browser, the intern will enable actual
browser to perform some action on the target web app which is under testing.
ACTUAL BROWSER
▪ These are the real browsers or s/w with user interface (UI), where we can access the web app.
▪ It needs the proper internet connection to process the request and response with respective server of
the web app.
INTERFACE
CONCREAT CLASS
Sachin M H
▪ Dotted line represents implement keyword.
▪ Normal line represents extended keyword.
SEARCH CONTEXT-
▪ It provides search mechanism to search the elements in the web page.
▪ It is an interface which contains two abstract methods.
▪ 1)findElement()- to search single element.
▪ 2)findElements()- to search multiple elements.
TakeScreenShot (Interface)
▪ It provides a way to take the page or element screenshot of the app under testing.
▪ It is an interface which contains only one abstract method that is getScreenshotAs().
JavaScriptExecutor(interface)
▪ It is an interface which contains two abstract methods.
▪ It provides a way to write java script programs in selenium.
▪ 1) executeScript() – to write synchronous javascript program.
▪ 2) executeAsynScript() – to write asynchronous javascript program.
WebDriver (Interface(i))
▪ It provides a way to control the browser.
▪ It is an interface which has 11 abstract methods.
▪ 1) get().
▪ 2) getTitle().
▪ 3) getCurrentUrl().
▪ 4) getPageSourse().
▪ 5) getWindowHandle().
▪ 6) getWindowHandles().
▪ 7) close().
▪ 8) quit().
▪ 9) navigate().
▪ 10) manage().
▪ 11)switchTo()
▪ This is the core interface of selenium without which we cannot start automation because it contains
main browser controlling methods.
▪ WebDriver is an object representing the browser, which can be used to control different browsers.
RemoteWebDriver(Concrete Class): -
▪ It is an implementation concrete class for lot of interfaces in selenium and also it is used mainly to
run the automations scripts from the host computer to the remote computer.
(Selenium Grid).
Sachin M H
BROWSER RELATED CLASSES-
▪ Browser related classes are used to perform –
▪ 1) starting their own servers (Driver Executable s/w).
▪ 2)Launching their own respective browsers.
▪ 3) Appling some browser level settings.
▪ All the 6 browser related classes are concrete classes, here the advantage of this is object can be
created or else implementations can be done.
INHERITANCE-
▪ Browser specific classes – remote web driver- Hierarchical Inheritance – Multiple child having
common parent.
▪ Remote web driver – interfaces (TakesScreenshot/WebDriver/JavascriptExecutor)-Multiple
inheritance – RemoteWebDriver Concrete class is providing implementations for all the 3 interfaces.
▪ RemoteWebDriver – WebDriver – SearchContext – Multi level inheritance.
Sachin M H
LAUNCHING EMPTY CHROME BROWSER
It’s the best practice to store the driver software within the project directory and provide the relative
path.
DOT represents the current project.
Unchecked Exception
Take viv notes and complete
1. ClassClassException
2. InputMismatchException
3. ArrayIndexOutOfBoundsException
4. AirthematicException
Sachin M H
5. NullPointerException
6. NumberFormatException
7. NoSuchElementException
8. MissingResourseException
9. IllegalStateException
Checked Exception
• The exceptions which are checked during compile time is known as Checked Exception
• Try catch block or by using throws keyword we can handle checked Exception.
IO exception
1. ClassNotFound
2. InvocationException
3. FileNotFoundException
Web URL
• Web uniform location (URL): uniquely identified the specific web resource inside the web
application.
• Every web application should have its unique address in the form of URL.
• URL is one and only way to access web application via browser.
• http://localhost:8080/login.
• https://google.com/search?q=iphone11.
• Maximum no of character in the URL is 200.
• http://172.217.160.142/search?q=iphone11.
PROTOCOL
• Protocol is common language where two applications exchange information with each other.
• When an application wants to communicate with each other (in our case browser & server),
There need to be a common language where both applications can understand each other.
• This language is known as protocol, where protocol has set of rules and instruction.
• Browser always sends a request & receive response via http protocol hence it is called http request /
http response.
• It is an optional information and case insensitive.
TYPES OF PROTOCOL
• http
• https
• ftp
• smtp,etc
Sachin M H
DOMAIN
• Uniquely identify the specific computer in the network in which web application is present.
• Domain name might be computer name or IP address.
• It’s a mandatory information and case sensitive.
• .com
• .gov.in
• .org
• .edu
PORT: -
• Uniquely identify the specific s/w or application inside the computer.
• In the URL this an optional information.
• http Tomcat 8080
• http Joss 80
• http WebLogic 123
• https Tomcat 8443
• https jboss 443
• https WebLogic 456
PATH: -
• Uniquely identify the specific web resource inside the application Server (web application).
• W2 1e Know web application is a collection of web resources, so its’s full of paths i.e. web
resources at the web application side.
FARGAMENT ID-
• Identify the specific fragment/section in the webpage.
• It’s an optional information in the URL.
Sachin M H
WebDriver
get()-
signature: public void get(String URL){
}.
Usage: driver.get(“Fully qualified main URL”)
• it is used to navigate main URL of the application.
• URL should be passed in the string form.
• The URL should be fully qualified (with its protocol).
getTitle(): -
signature: : public String getTitle(){
}.
Usage: String CapturedTitle = driver,getTitle();
• This method is used to get the webpage title.
• It returns the webpage title in the string form.
• This method will be used to verify the title of any webpage of the application under testing .
contains(CharSequence…ch): -
• contains() – method.
• It will check whether the condition is true/not.
• Equals/not equals
• Return type of this method is Boolean.
• Used to compare two strings.
4)getCurrent(): -
signature: public void getCurrentUr(){
}.
Usage: currentUrl=driver.currentUrl().
getPageSource()
signature: public String getPAgeSource(){
}.
Usage: pageSource=getPageSource().
Sachin M H
WebPage
getWindowHandle(): -
signature:
public String getWindowHandel()
Usage:
String windowIdUnderControl=driver.getWindowHandel().
• This method is used to get the window id.
• Current Window ID mean, the current window on which the driver control is available.
• Initially the driver control will always lie in the parent window and will get the same window id.
• It gives the window id in the string form.
getWindowHandles(): -
signature:
public String getWindowHandels()
Usage:
Set <String> allWindowIDs=driver.getWindowHandels().
Sachin M H
close(): -
signature:
public void close(){
}
Usage:
driver.quit().
• This method will close the current browser window.
• NOTE: close() will only close the current browser window among the group of windows. As
initially the driver will be pointing to parent window, so close() will have control to close only that
parent window.
• NOTE: we can also transfer the driver control to other windows. In such scenarios depending on
where the driver control is available, that browser window will get closed.
Close() Quit()
It will close the current browser window. will close all the browser windows.
Close() will not stop the server. quit() will stop the server.
We should not use close() as post condition We should use quit() as the post condition.
Navigate(): -
signature:
public Navigation navigate()
• Navigate() is used to perform browser history navigation like back, forward, refresh.
• Navigate() is also used to navigate to the sub URL of any web application.
• It returns navigation type object.
• Navigation is an interface in selenium which contains 5 Abstract methods.
• RemoteNavigation is the concrete class, it will provide implementation for all the 5 methods
• back() – void
• forward() – void
• refresh() – void
• to(String URL)- void
• to(URL url)- void
navigate(): -
• navigation is an inner interface of WebDriver.
• Remote navigation is an inner concrete class of RemoteWebDriver Class.
• If return type of any method is parent type then that method can return the child objects as well, so
while returning auto upcasting will happen.
• Public Fruit getFruit()
{
Return new Apple();
}
Sachin M H
(upcasting) (downcasting)
• EX: attachment, Here getFruit() Is returning Fruit type object. So, here fruit is the parent and Apple
is the child. Auto Upcasting will happen while Fruit type object is returned.
• Public Navigation navigate()
{
Return new RemoteNavigation();
}
• Navigate() internally creates the object of RemoteWebDriver class and returns it in the upcasted
form yo its parent Navigation.
back(): -
• Signature : public void back()
• Navigates to immediate Previous page in the same session.
• Usage: - driver.navigate().back();
forward(): -
• Signature: public void forward(){}
• Navigates to immediate next page which we loaded.
• Usage: - driver.navigate().forward();
Refresh(): -
• Signature: public void refresh()
• Reloads the same webpage one more time.
• Usage: driver.navigate().refresh();
to(String url): -
Signature:
public void to(String url)
Usage:
driver.navigate().to(“sub URL”);
• This method is used to navigate to the sub url of the application get() method will be used.
• If any test case doesn’t mention how to any sub page of the application then we can directly go to
the webpage by using the url of the page using navigate().to()method.
• But internally coding of get() and navigate().to() is same, but only usage is different.
Sachin M H
What is the difference between get() and navigate().to()??
There is no difference between these two methods implementations. We can find the difference in
the usage. As a best practice get() is used to navigate to main url and navigate().to() is used to navigate to
sub url.
Get() Navigate()
It is used to navigate to main url of the It is used to navigate to the sub url of the
application i.e. we can use it only for url application and also we can perform browser
navigation. history navigation’s like back, forward and refresh.
The return type is void the return type is navigation type object
to(URL url): -
• This method accept URL concrete class object as an input.
• URL class concrete class of java.netpackage.
• Using URL class we can compose the url’s is different ways.
• URL constructor throws a checked the url’s is different ways.
• URL constructor throws a checked exception called as MalformedURLException.
• MalformedURLException is a checked exception of java.netpackage, which will occur whenever the
protocol is not specified while URL creation.
• As it is checked exception we can handle it during compile time itself either by using try, catch
block or by using throws keyword.
• URL- Uniform Resource Locator.
• Dynamically composed URL will be used here by using URL Class we have multiple Constructors.
Java Concepts
• Constructor overloading – same name different argument under the same class object creation.
• Here java URL Class provides different constructor and we witness constructor overloading.
Manage(): -
• Signature: public Option manager()
• Usage opt=driver.manage();
• Manage() used to perform the following operations.
1. Window related operations.
2. Timeouts related operations.
Sachin M H
3. Cookies related operation.
maximize().
• Signature: public void maximize().
• Usage: driver.manage().window().maximize().
• It is used to maximize the browser window.
• It will be used as the precondition whenever we used write automation scrip t.
fullScreen().
• Signature: public void fullScreen().
• Usage: driver.manage().window().fullScreen().
• It is used to open the browser window in full screen mode.
getSize(): -
• Signature: public Dimension getSize().
• getSize() used to get the current dimension of the browser window.
• i.e. the height and width of the browser window.
• This method returns the Dimension class object.
• Dimension is the concreate class of the selenium package which contains two method
getWidth() and getHeight().
• Usage:
• Dimension size=driver.manage().window().getSize();
• Int height=size.getHeight();
• Int width=size.getWidth();
Minimize(): -
• Signature: public void minimize().
• Usage: driver.manage().window().minimize().
• It is used to minimize the browser window.
• It will be used as the post condition in the automation script.
setSize(): -
• Signature: public Dimension setSize(Dimension targetSize).
• Usage:
• Dimension targetSize=new Dimension(int height, int width);
Sachin M H
• Dimension size=driver.manage().window().setSize(targetSize);
• This method is used to re-size the browser window
• This method accepts Dimension class object as input.
• So, we should create the dimension class object with the target width and height and later we
should call the setSize() and supply the created Dimension type object as an input.
getPosition(): -
• Signature: public point getPosition().
• Usage:
• Point position= driver.manage().window().getPosition();
• Int startx=position.getx();
• Int startY=position.gety();
• getPosition() is used to get the browser window X and Y coordinates.
• getPosition() returns the point class object through which we can get the
X and Y coordinates by calling getX() and getY().
• getX() will return the startX value and getY() will return the startY value.
setPosition(): -
• Signature: public void setPosition(Point targetPosition)
• Usage:
• Point targetPosition=new Point(int x, int y);
• Driver.manage().window().setPosition(targetPosition);
• This method is used to move the browser window.
• setPosition() accepts point class object as input.
• So, first we should create the point class object with target x and y coordinates and later we
should call setPosition() and supply the point object as input.
switchTo(): -
• Signature: public TargetLocater switchTo()
• Usage: driver.switchTO().window(String windowID);
TargetLocater(i)
window()
Frame()
Alert()
activeElements()
Remote Target
Locater
1. This method is used to transfer the driver control to –
Sachin M H
• Window
• Alert pop-up
• Frame
• Active element of the webPage
2. This method returns the target locater type object.
3. To transfer the webdriver control to the window(), we should use window method and pas s the
window ID to it.
Sachin M H
HTML(HYPER TEXT MARKUP LANGUAGE): -
<html>
</head>
<body>
<input type=”text”>
<button type=”submit”>click Me!!</button>
<a href=”https://www.google.com”>Google</a>
<input type=”radio”>
<input type=”password”>
<input type=”checkbox”>
<span>Mohan</span>
</body>
</html>
INTRODUCTION
• Hypertext Mark-up language.
• It is used to display the content in the structured format.
• It is not case sensitive.
• All the codes are considered as tags.
• Tag will be represented with angular brackets [].
• It is nested language / it has tree structured.
• All the HTML program will be saved with Filename.html extension.
• The root tag of HTML program is <html>.
• Majority of the tags will have closing tag.
What is a tag??
1. The angular bracket in html program is called as tag.
2. All the html program elements are called as tags (something like tokens in java).
What is an Attribute??
1. The key and value pairs within the tag is known as attribute
2. A tag can have zero or more attributes.
3. Ex: <input type=“text” placeholder=”enter”>
4. Ex: <a href=” https://www.google.com”>
Sachin M H
What is Attribute value??
The value of the attribute is called Attribute value.
Some attributes may or may not have values.
Ex: <input type=”text” placeholder=” enter” value””>
What is text??
Any thing which comes in between opening and closing tag is considered text.
Ex:<span>Hello</span>.
<p>welcome to india</p>.
Web Element
14+1+2=17
14+1+2=17
POSSIBLITY NO 2
1. C lick on setting by …on top right of the window.
2. Click on more tools.
3. Click on developers tools.
4. Click on elements tab.
5. Click on mouse pointer icon.
6. Place the mouser curser on the target element and click on it.
POSSIBLITY NO 3
1. Press CTRL + Shift + i.
2. Click on elements tab.
3. Click on the mouse pointer icon on top left of source code.
4. Place mouse curser.
Sachin M H
LOCATERS
INTRODUCTION
• Locaters are the search criteria through which we can find the elements in the web page.
• Locaters are also called as selectors.
• Selenium provides 8 locaters strategies to find the element in the web page they are:
1. id
2. name
3. className
4. linkText
5. partialLinkText
6. tagName
7. cssSelector
8. xpath
NOTE:
1. Here id, name and class are the attribute names in the source code of any web element.
2. cssSelector and xpath are the Expression which can be used to fin the element.
3. Selenium developers provided a class called By in which all the locaters related methods are
available.
4. By is an abstract class which contains 8 static methods which can be used to find the element in the
web page.
By abstract class By
{
Public static By name(String nameValue)
{
=========
=========
}
Public static By tagName(String tagname)
{
=========
=========
}
Public static By linkText(String linkText)
{
=========
=========
}
Public static By partialLinkText(String linkText)
{
=========
=========
}
Sachin M H
Public static By cssSelector(String expression)
{
=========
=========
}
Public static By xpath(String expression)
{
=========
=========
}
}
• To use all the static methods we should use it in findElement() or findElements() as shown below.
• By.id(“idvalue”);
• By.name(“namevalue”);
• By.className(“classvalue”);
• By.tagName(“tagname”);
• By.linkText(“fulllinktext”);
• By.partialLinkText(“full / partial linktext”);
• By.cssSelector(“cssExpression”);
• By.xpath(“xpath Expression”);
What is findElement()….??
• It is an abstract method of SearchContext interface which is used to
• If the element is found, it will return the address of that element or in other words if the element is
found it will return the WebElement interface type object using where we can perform some actions
on it.
• WebElement element = driver. findElement(By.id(“LoginButton”);
• If the element is not found with the given locater strategy then findElement() will throw
NoSuchElementException.
• If the given locater strategy is matching with the multiple elements then findElements() will return
the first matching element.
• Signature: public WebElement element= driver.findElement(By.(“username”));
• Element.clear():
• Element.sendKeys(“admin”);
• Ex:→ driver.findElement(By.id(“LoginButton”)).click();
•
NoSuchElementException
• It is an unchecked exception of selenium which will be thrown:
• If the locater strategy is incorrect.
• If the element is not loaded (due to slow internet connection)
Sachin M H
NOTE
• Whenever the browser object to webdriver interface type reference then we can access only web
driver interface methods and its parents i.e., SearchContextInterface .
• Webdriver driver = new WebDriver();
• We are achieving this by auto upcasting.
• Other methods will be available in the browser object due to inheritance but not accessible through
WebDriver reference.
• ChromeDriver driver = new ChromeDriver();
• So to access them we need to downcast to their interface type.
NOTE:-
• generally By.tagName() and By.className() are used to identify multiple elements because of this
the chances of duplicates are more.
• By.classNAme() won’t identify the element if the attribute value is having a space and it gives
InvalidSelectorException.
NOTE: By.linkText()
• This locaters strategy will be used to identify the <a> Since the link is large enough I its length that
will be represented with the name of the link, we call it as linkText.
NOTE: By.partialLinkText()
• Here also link will be stored within then<a> because the name of the link is dynamic in nature this
leads to the usage of By.partialLinkText() locater.
• Ex:- in Gmail application, Inbox(31),Inbox(41)
NOTE: By.tagName()
• This input is more suitable for findElements(), because w.r.t tagName there are lot of duplicates will
be their.
NOTE: By.cssSelector()
Css stands for (CASCADING STYLE SHEETS) it is a language which is used to apply styling to
the web elements like :
1. Decorating the group of text with the same color, font face, style, etc.
2. Applying the background color for group of buttons.
3. Applying the mouse overring color for the group of elements.
4. Css is embedded along with html.
Sachin M H
5. CssSelector is a query language which is used in CSS to identify group of elements in html on
which we can apply common styling.
6. As in automation also we need to identify the web elements by using CSS selector.
7. Whenever the source code of the web element does not have id, name and class attributes and if the
web element is not link text then to search that element we should use css selector.
• Syntax:→ tagName[attName=’attValue’]
o Ex: input[type=’submit’]
Button[id=’btn1’]
Input[class=’textField’]
• Shortcut syntax to id in cssSelector: - tagName#idvalue
o Ex:- button#btn1
Shortcut syntax to class in CSS selector: -
tagName.classvalue
• Ex03:input.textfield
DISADVANTAGE OF cssSelectors
• cssSelector does not support text function (i.e., if the source code of the WebElement is not having
any attributes just the text then we cannot use cssSelector )
• usage Ex: -
• driver.findElement(By.cssSelector(“input[‘text’]”)).sendKeys(“admin”);
• we cannot perform backward traversing using cssSelector.
What is an InvalidSelectorExcption???
• It is an unchecked exception of selenium which will occur when syntax of cssSelector / xpath is
incorrect.
• NOTE: it a best practice to verify the css and xpath expressions in the browser itself before using it
in the automation script.
1. To verify the expressions in chrome:
• Inspect the target element.
• CTRL+f in the elements tab.
• Then write the expression and verify in the search string, selector and x-path textbox.
2. To verify the expression in the firefox:
• Inspect the target element.
• write the expression and verify in the search HTML text field.
Sachin M H
XPATH(XML path)
1. Xml can be abbreviated as extensible markup language.
2. XML is like HTML language but it is used as a standard format for data exchange between client
and server and between two different applications.
3. Xpath is a query language which is used in XML to identify the XML elements. As the XML and
the HTML are having same program elements we can use xpath in html also.
4. Xpath is the path or address of the web element in the HTML tree structure.
WHY XPATH…??
1. If the source code of the element not having any attributes, but just the text, we should use xpath.
2. If the elements are completely dynamic oe if there are duplicate elements we should use xpath.
3. If the source code of the element is not having id, name or class attributes and if their was no link
then we should use xpath.
TYPES OF XPATH
Based on where the xpath starts, it is classified into two types: -
1. Absolute xpath
2. Relative xpath
Absolute xpath
1. If the xpath expression starts from the root of the HTML doc then it is called as absolute spath.
2. Here we use two symbols DOT(.) and Forward Slash(/).
3. Dot(.)means current document or current webpage.
4. Forward Slash(/) means immediate child.
5. If the xpath matches with the multiple elements then the xpath will store those elements in the array
<html>
<head>
<title>For Absolute Path</title>
</head>
<body>
<div>
<input type=”text” value=”A”>
<input type=”text” value=”B”>
<div>
<div>
<input type=”text” value=”C”>
<input type=”text” value=”D”>
</div>
</body>
</html>
structure which is xpath Array Always xpath Array index starts from 1.
Sachin M H
A→html/body/div[1]/input[1]
B→html/body/div[1]/input[1]
C→html/body/div[2]/input[1]
D→html/body/div[2]/input[1]
AB→html/body/div[1]/input
CD→html/body/div[1]/input
Sachin M H
DISADVANTAGES OF THE ABSOLUTE XPATH:
1. It is very length and time consuming because as we write the path from the root of the document.
2. Here there are more chances of using index. So, if the position of the element changes then we need
to modify the index used in the xpath again and again which needs more maintains effort.
3. So for above two reason absolute xpath is not used in real time.
RELATIVE XPATH.
• If the xpath starts from any child of the document or webpage then it is called as relative
xpath.
<html>
<head>
<title>Relative xpath</title>
</head>
<body>
<input type=”text”value=”A”>
<input type=”text”value=”A”>
<input type=”button”value=”A”>
</body>
</html>
A-----//input[1]
B-----//input[2]
C-----//input[3]
AB-----//input[1]//input[2]
BC-----//input[2]//input[3]
Sachin M H
ABC-----//input
• Here also we may need to use index to identify the elements uniquely, in such cases the relative
xpath should not be as their will be too much of maintenance efforts if the position of the element’s
changes.
• In real time this type of xpath used to identify multiply elements.
o Ex: Identify all the links of webpage, images.
• NOTE: IT IS ALSO USED TO IDENTIFY THE FIRST ELEMENT OR LAST ELEMENT OF THE
WEBPAGE.
DRAWBACKS
• Here also we have to use the index to identify the element uniquely, in such case correlatively xpath
should not be used as their was too much of maintenance effort is needed.
!!!!!!!!!!!!!!!INTERVIEW QUESTIONS!!!!!!!!!!!!!
Write an xpath to identify all the links and images present in the webpage??
• //a|//img.
Sachin M H
XPATH By attribute: -
• Writing a relative xpath by using attribute is called as xpath by attribute.
• General syntax:
//tagName[@attributeName=’attributeValue’]
• @ is compulsory while writing xpath by attribute.
• <button type=”submit”>sign in
Xpath by text()
• <html>
<body>
<span>Fruit</span>
<span>
<b>Fruit</b>
</span>
</body>
</html>
Syntax: //tagName[text()=’CompleteTextValue’]
in the above syntax text value is :-
1. Case sensitive
2. Should be the complete text
Sachin M H
3. It allows both the normal and link text.
Syntax ://tagName[.=’textValue’]
• Dot function will identify both the tag text and also sub tag text.
• Xpath to identify both the fruit and apple in the current web page is
//span[.=’Fruit’]
• Text function will identify only tag text
//span[text()=’Fruit’]
• Here though the above xpath works fine now, when the developer changes the year to 2021
then the xpath will not work. So we should not use xpath by text function in the above
scenario.
• If the text of the target WebElement is very lengthy the by default xpath will be lengthier. In
such cases if we have to same give the same partial text, text() will not work because it needs
complete text. So it is not the best practice to use next function in such cases.
• Example: - //td[text()=’Shree Dharmasthala Manjunatheshwara Engineering
College,All rights Reserved’].
• The above xpath is very lengthy
Xpath by contains()
• Writing the xpath to identify the target WebElement based on its partial text and partial attribute
value Is called as xpath by contains function.
Contains by text(): -
Syntax: -01) //tagName[contains(text(),’partialTextValue’)]
Sachin M H
Syntax: -02) //tagName[contains(.,’partialTextValue’)]
• .(Dot) will select all similar tags having the same text value.
Contains by partialAttributeValue
• Writing the xpath using partial attribute value can be considered as xpath by contains function usin g
attribute.
• Syntax: -01): - //tagName[contains(@attributeName,’partialAttributeValue’)]
Note: - Completely dynamic text means the text which changes completely always.
https://www.irctc.com/Contact.html
observe the table data such as phno , mailId of the different trains.
Independent/dependent X-path
It is the procedure to identify completely dynamic/duplicate elements using other types of x -path and also
by using backward Traversing (/..).
Sachin M H
3. Step 02) identify which element is fixed and which element dynamic. Buddhist train is the fixed
element. Help line no is Dynamic.
4. Step 03) Write the xpath to identify the fixed element??
a. //td[text()=’ Buddhist train’]
5. Update the xpath to identify the immediate common parent by using backward Traversing ( /..).
a. //td[text()=’ Buddhist train’]/..
Here the xpath written for the WebElement itself is having duplicate’s. That means the address itself has
got duplicated because of similarity In the fixed element which we have chosen for the corresponding
dynamic element.
This is the clear situation / scenario where we cannot identify the element by using independent and
dependent x-path approach.
Syntax: (xpath)[indexValue]
What is X-path by group index..??
Writing relative x-path to identify unique element among group of duplicates using is called as X-path by
group index.
http://money.rediff.com/gainers
identify previous price of the tata teleservices in the table.
(//a[contains(text(),”Tata Teleservices(M’)”)]/../..//td)[4]
Note:
• We should group by index only if necessary and we should keep it as last option, because of the
position of the element changes then we need to modify the xpath which involves more maintenance
effort.
• But whenever the scenario it self is demanding index then we must use, as shown below.
Sachin M H
Write an x-path to identify the 1 st link in the webpage..?
• (//a)[1]
Write an x-path to identify all the links which are starting form 4.1 in selenium WebSite
• (//a) [Starts-with(text(),’4.1’)]
Note: -
• There is no first(0 in X-path.
• There is no ends-with() in X-path.
Sachin M H
❖ X-path by axes
<table> ➔Ancestor
<tr>➔parent
<td>Java</td>
----------------------------------<td>Selenium</td>------------------------------------------
<td>SQL</td>
</tr>
<tr>
<td>
<div>Automation</div>
</td>
</tr>
</table>
• Axes is plural form of Axis
Parent axes: -
• This axes will identify the parent element from the current fixed element.
Note: -it is same as using /.. operator.
Child axes: -
• These axes will identify the child element from the fixed element.
Note: -it is same as using / operator.
Descendant: -
• This axes will identify all the descendants i.e. child/grandchild and so on from the context/fixed element.
Note: -it is same as using // operator.
Ancestor axes: -
• This axes will identify all the parent, grandparent and so on from the context/fixed element.
Note: -it is same as using /.. operator.
Sachin M H
Following axes: -
• This axes will identify all the element which are appearing before context/fixed element.
Following-Sibling axes: -
• This axes will identify only the sibling of the fixed element which comes after context/fixed
element.
Preceding-sibling axes: -
• This axes will identify only the sibling of the fixed element which comes before context/fixed
element.
Preceding axes: -
• This axes will identify all the element which are appearing before the context/fixed element.
Note: -
1. we can use * (symbol) in the place of tagName in the X-path in such case it will identify target
element with any tagName based on the given condition.
Ex: //*[@id=’LoginButton’]
Here the above xpath identify the element with any tagName which
2. The above kind of xpath generally used in identifying the mobile web elements in Appium(mobile
testing) because all the tagname’s will be same most of the time.
3. Some graphics related tagname’s will not be identified through X-path directly, in such case we can
use.
Example: - //svg[@id=’users’]
SVG➔Scalable Vector graphics
4. Here SVG is graphics related tag through which x-path will not identify, but if we use * in place of
SVG tagName then x-path will identify.
Example for x-path by axes
• In some scenarios using the index will be the only option as shown in the below example.
• URL: - https://money.rediff.com/gainers.
Sachin M H
Write an x-path to identify national fittings previous closure.=======➔try this at home
• //a[contains(text(),’National Fittings’)]/../following-sibling::td[2]
• Here we have to use the index since td tag has no attributes and also text is completely dynamic.
• This makes you to use x-path by index without any second thought.
!!!!!!!!!!!!!!!INTERVIEW QUESTIONS!!!!!!!!!!!!!
What is WebElement..?
What is findElement..?
What are locaters and explain all the locater type..?
What is by class..?
What is no such element exception..?
What is css selector and why we should use css selector..?
What is x-path and why we should use x-path..?
What are the different types of x-path..?
Write the syntax of relative x-path with an example..?
what are the difference b/w css selector and x-path..?
what are the priorities of locaters..?
WebElement
Click()
• It is used to click on the target WebElement.
• Target WebElement can be :-
1)Button
2)RadioButton
3)textField
4)checkbox
5)link..etc.
it performance 2 operations.
1. It will scroll the target WebElement to the visible or viewport area of webpage to same extend
2. It clicks on the target WebElement.
3. if it is not able to click on target WebElement then it will through
elementClickInterceptedException(it is an unchecked selenium exception)
4. We will get the above exception whenever the target element is obscured or hidden by some other
web element.
5. It will not receive any argument and the return type of click method is void.
• Signature: - public void click()
ele.click();
Sachin M H
What is element click intercepted exception..?
• It is an unchecked exception of selenium which will be thrown by click() when ever the target element is
obscured or hidden by another element.
• There Two ways to handle this exception
1)Handel the element which is obscuring the target element.
2)using the java script executor.
Clear()
Signature➔public void clear()
Usage➔ele.class();
sendKeys()
Signature➔Public void sendKeys(CharSequence…keysToSend)
Usage➔ele.sendKeys(“admin”);
Ele.sendKeys(“KeysEnter”);
• IF the keyboard action cannot perform on the target WebElement then it will throw element
Noninterpretable Exception
• Enum stands for Enumeration and it is one of the java templates.
• Note: 1)CharSequence is an interface in java which was implemented by stri ng and string Builder
classes
2)Keys enum is also implemented by CharSequence interface of java.
3)So for this reason sendKeys() can supply string as an input, StringBuilder as an input and
keys enum as an input.(auto upcasting)
Sachin M H
4)IllegalArgumetException is unchecked exception of java.
getText() -27/05/2022
Public String getText()
ele.getText();
Note:
• getText() Will return both the tagtext & Subtagtext. This behavior of getText() is sometimes an advantage
Sometime its an disadvantage.
• Advantage in calendar popup.
getAttribute()
Signature:-
Public String getAttribute(String attribute name)
Usage
String attributeValue = ele.gatAttribute(“placeholder”)
• This method will return the value of the given attribute name of target WebElement.
• The argument of the method is String type and it will the string.
• If the given attribute name is not there with target element then it will return null.
• It is used to verify the attribute value of the WebElement like
1. Verifying tool tip text.
2. Verifying Alternative text.
3. To verify the placeholder text.
4. To v erify the textField is empty (or) not.
GetCssValue()
Signature: -
Public string getCssValue(String property name)
Usage:-
String propertyValue=ele.getCssValue(“property value”);
• This method is used verify the styling information of the target WebElement.
• This method accepts the Css property name as an input in the String form and returns the value associated
with that property in String form itself.
• If the property name is not having any value in such case it returns empty String . so by using this method
first verify whether the written value is empty or not .
Sachin M H
Ex:-
1. Verifying the background color of the button.
2. Verifying the color of the text.
3. Verifying the boldness of the text.
Note:-
1. To see the Css property and values of the target WebElement:-
2. Inspect the target element.
3. Go to the computed tab, which is at the right side of the browser window.
Note:-
1. color is selenium class through which we can convert given rgb value into hexadecimal code.
2. Form String (rgb value) static method of color class which returns the color class type object itself.
3. asHex() is the nonstatic method of color class which returns the hexadecimal code for the supplied rgb value
in form of string.
Note:-
• It is always but practice to compose the color is the hexadecimal color code format instead of the comparing
him rgb.
Note:-
1. Rgb are primary color through which any color can be created.
2. Highest value is 255.
3. Ex: -(0,0,0) is prefect black.
4. (255,255,255) is perfect white.
Hexadecimal value color code is the number used to r4epresent the rgb value.
#000000 Black
#FFFFFF
Hexadecimal value contains o to 9 and ABCDEF. This combination is nothing but hexadec imal value.
Property name : font-weight
100 Thin(hairline)
200 Extralight(ultra light)
300 light
400 normal
500 Medium
600 SemiBold(Semi bold)
700 Bold
800 ExtraBold(ultraBold)
900 Block(heavy)
isEnabled()
Signature:-
Public Boolean isEnabled()
Usage: -
If(ele.isEnabled())
{
}
else
{
}
• IsEnabled() used to verify weather target WebElement is Enabled (or) not.
Sachin M H
• This return type of this method Boolean, if it is return’s true then target element enabled other wise it is
disabled.
Note:-
1. IsEnabled() works properly only on input elements i.e,<input>tag and <button>tag
2. If it is called upon any other element then it will return always true through the element is enabled or not.
3. So in such cases we should find the proper work around.
IsSelected()
Signature:-
Public Boolean isSelected()
Usage:-
If(ele.isSelected()){
}
else
{
}
• This method is used to verify the status of radio button or check box
• If you use it on other elements then it will give you unpredicted o/p
• The return type of this method is Boolean. It returns Boolean true if it is Selected, false otherwise.
Note:-
isSelected() give unpredicted results if target element is not a radio button, checkbox and option of dropdown list
box.
If it is yes on same other element in that case it will return false irrespective of weather target element is selected or
not selected.
isDisplayed()
Signature: - public Boolean isDisplayed()
Is(ele.isDIsplayed()){
}
Else{
` }
• It is used to check the target WebElement is displayed(visible) or not.
• Return type is Boolean
• If it is return’s true: element is present and it is displayed.
• If it is return’s false: element is present but not displayed.
Note:-
This method can be used to verify both the element is present in DO< and weather it isDisplayed or not.
getSize()
Signature: -
Public Dimension getSize()
Usage: -
Dimension eleDimension=ele.getSize();
Int eleHeight=eleDimension.getheight();
Int elewidth=eleDimension.getwidth();
• This methos used to get the size of target WebElement.
Sachin M H
• It returns dimension class object.
• Using the dimension class object, we can get the height and width of the target WebElement, i.e We have to
call get height() and getWidth() or dimension object.
getLocation(): -
Signature: -
Public Dimension getLocation()
Usage: -
Point eleposition = ele.getLocation();
Int start x = eleposition.getx();
Int start y = eleposition.gety();
➢ This method is used to get the co-ordinates of the target WebElement.
➢ It represents the point class object.
➢ Using point class object we can get x and y co-ordinates of the target WebElement, i.e, we have to call
getX() and getY() of the point class type object.
getRect(): -
Signature: -
Public Rectangle getRect()
Usage: -
Rectangle Rect = ele.getRect ();
Int eleHeight=eleRect.getHeight();
Int eleWidth=eleRect.getWidth();
Int ele StartX=eleRect.getX();
Int ele StartY=eleRect.getY();
➢ This method is used to get both size and co-ordinates of the target WebElement.
➢ It returns rectangle class object.
➢ Using rectangle object we can the size and co-ordinates y.e, by calling getHeight(), getWidth(), getX(),
getY().
Note:
➢ Dimension, point and rectangle are concrete classes of selenium library. We should always import it from
selenium package before using if it in the code.
➢ getX and getY always returns the starting x co-ordinates value i.e, startY, by using this we can calculate end
point.
!!!!!!!!!!!!!!!INTERVIEW QUESTIONS!!!!!!!!!!!!!
WHAT IS USE OF GetSize(),GetLocation, GetSize()..?
1. All the method used to verify the arrangement of target WebElement like verification of the left, right and
top alignment of the webpage.
2. Sometimes there might be issues with alignment while testing on different browsers.
Submit(): -
• It is used to click on the submit button.
• Submit button means:
Sachin M H
o The button element should contain type=”submit”.
o The <button> should be the sub tag of the <form>.
o <form>
<button> type=”submit”</button>
</form>
• If the method button is called on any element apart from submit button then it will throw
JavaScriptException/the action won’t be performed.
• This method will click on the submit button and if there is page redirection then it will wait until the
next page has got loaded.
• JavaScriptException is an unchecked exception of selenium which will be thrown when there is
mistake in the program/script and also when submit () is not used on the submit button.
getTagName()
Signature: public String getTagName()
Usage: ele.getTagName();
If(ele.getTagName().equals(“input”))
{
ele.clear();
ele.sendkeys();
ele.submit();
}
• This method is used to get the tag name of the target WebElement.
• It is used to verify the TagName of the target WebElement.
• It returns the tagName in String form.
• It is generally used in library methods to verify the tagName of the target WebElement to perform
the desired task.
What are the different ways of removing the text from the text field..??
➢ Clear();
➢ By using sendKeys() with keyboard shortcuts like:
o keys.CTRL+”A”
Sachin M H
o keys.DELETE.
How do you write the log statements/what are the plugins you are aware of to write the log
statements..??
➢ Log4j.
➢ testEng-repoter.
➢ Extend-reports. -----→comes under advance selenium.
Sachin M H
Handling forms, tables, divisions using child element.
SearchContext
TakeScreenShot
findElement()
getScreenShotAs() findElements()
Web Element
14+1+2=17
implements
WebElement-14
TakeScreenShpt-01
SearchContext-02
findElement()
findElements() Driver.findElement().findElement();
Sachin M H
Remote WebElement implementation
➢ It is to identify parent element in webpage.
➢ The search for target element begins from the beginning of the webpage or html tree.
➢ Here search for the target element begins from the beginning of the webpage or html tree.
➢ The RemoteWebElement implementation
o It is to identify the element within particular area or the WebPage or within the particular
parent element.
Note: -
➢ Search happens only within the parent element.
➢ use . at the beginning of the x-path for identifying child elements or else no need to use // i.e. just
use the tagName with the predicate (if required).
Sachin M H
SYNCRONIZATION
WHAT IS SYNCRONIZATION...??
➢ Synchronization is a process of matching two different events according to the requirement of the
system, to get the desired outcome.
➢ In automation, we had to match the application loading speed and the automation script execution
speed to get the proper results.
➢ The process is called as Synchronization in automation.
➢ Generally, the automation script execution speed is faster than the application loading speed. So we
have to apply delays, in the automation script to match the application loading speed.
➢ There are 5 ways to achieve Synchronization.
o Implicit wait.
o Explicit wait.
o Fluent wait.
o Thread. Sleep wait.
o pageLoadTimeOut.
Note:
➢ application loading speed will be slow due to
o slow internet connection.
o Poor business logics written in the webserver.
Element is
Is the time Wait for 500
present in
over? milliseconds
html? NO NO
Polling period/
Wait frequency/
Time interval
YES YES
Note:- this implicit timeout is applicable for each and every call of findElement() and findElements().So
generally it will be applied at the beginning of the automation script as precondition.
It is one of the intelligent waits in selenium WebDriver which helps us to save time while we wait for:
o Expected title of the webpage to load.
o Expected URL of the webpage to load.
o to reach the clickable state.
Sachin M H
o Image to be visible on the webpage.
o Alert to be present on the webpage and many more.
• Here we provide the time delay for the expected conditions to be successful.
• If the expected condition is satisfied anytime within the specified time delay then the load Does not
wait for the remaining duration. It releases the control to the next line of automation script.
• It uses 500 milliseconds or the search frequency/polling period.
• If the given condition is not successful within the specified time delay then they will get
TimeOutException with the appropriate error message.
Note:
1. Here expected conditions are called as predicates/predicates functions.
2. TimeOutException is an unchecked exception of selenium thrown when the explicit wait fails.
Until()
❖ Until() is nonstatic method of webdriver wait class, whenever we have we have multiple con ditions
the we can this method again and again.
❖ For each and every until() invocation the overall time delay is applied.
❖ Example: wait until(ExpectedConditions title(“Google”));
❖ ExpectedConditions is a concreate class of selenium and it is having lot of st atic methods which are
also known as predicate function.
❖ Depending on the conditions we have to use the various static methods of this class.
Note:
• If the static method which are not there as the condition specified than we can create our own
predicate function by using practice to create reference variable name as wait so that the code will
be more readable.
Sachin M H
Difference b/w implicit and explicate wait .
Implicit wait Explicit wait
• We need not specify waiting • We need specify waiting condition.
condition(built-in)
• We can handle the synchronization of all • We can handle the synchronization of any
the invocation of find element() statement but only one at a time.
• After specified time we will get • After specified time we will get
NoSuchElementException TimeOutException
getScreenShotAs()
Output type: -
Output type is an interface which contains 3 final variables which is used to specify th e target screenshot
type for getScreenShot as method, the final variables are:
FileUtils
• It is a class name.
o Signature: - public static void copyFile(Filesrc,Filedest)
▪ Usage: -try{
FileUtils.copyFile(tempFile,destFile)
}
Catch(IOException e)
{
e.printStackTrace();
}
1. It’s a concreate class of commons-IO library which is used to perform various File-IO
Operations.
2. In automation the scree shot taken by getScreenShotAs() is temporally, so to copy the temporally
file we have use FileUtils class.
3. It is having lot of static methods, one among them is copyFile().
4. copyFile() takes two arguments of file class type.
5. First argument is the source file and the second argument is the destination file.
Sachin M H
6. If the destination folder does not exist, it will create that folder then it will takes the screen shot.
7. It throws IOException in case of any folder access issues/some input/output issues while copying
the source to the destination file. As IOException is one of the checked exceptions, we need to
Handel it either with try catch block/with throws keyboard.
8. You should import this class from the commons-IO package.
❖ Whenever we are running automation scripts in real time we run them many times in a day/week so
if the files name are not unique then the screenshot will be overridden to the latest execution . So we
have to create a unique file name for the screen shot.
❖ To create unique file name for the screen shot we have to use the type stamp is nothing but the
system date and time.
❖ If we capture the system date and time and add it to the screen shot file then we can retain the screen
shot for all the executions.
❖ So to capture the system date and time we need to use the LocalDateTime concreate class of
java.time package.
❖ It contains the static method called now which returns the same class object using which we can get
the date and time.
❖ We have to call the toString method on the LocalDateTime object which returns the date and time in
string form.
❖ But the date and time string contains ‘:’ which is not a valid file name in the operating system, so
we have to replace the special char to some other valid char like ’-‘.
a. Signature:- public static LocalDateTime now()
i. Usage: - String timestamp = LocalDateTime.now().toString replace(‘:’ , ’-’);
Note:
i. As a standard practice all the Screenshots should be stored in project directly inside the folder called
Bug Shots.
Sachin M H
ii. Only the visible of the webpage will be taken in the screenshot.
iii. Current browser window screenshot will be taken, so to take other browser screen shot we have to
transfer the control to that particular window.
WebElement ScreenShot
TakeScreenShot
getScreenShotAs()
extends
WebElement
14+1
implements
RemoteWebElement 14+1
Sachin M H
FRAMES
WHAT IS A FRAME...?
• A frame is nothing but an imbedded webpage. Imbedded webpage means webpage inside another
webpage or html inside another html.
Sachin M H
If the source code of the target element ancestor is i-frame tag, then the element is present within the
frame.
Step 3)
In few webpages by seeing the GUI(graphical user interface) we can guess the target element is within
the frame/not.
Step 4)
Generally when we get NoSuchElement exception there can be lot of reasons-
c. May be synchronization issue
d. May be locater stagey is incorrect.
e. The element is present within the frame.
2. So, When we get NoSuchElement exception if everything is fine, then maybe the element is present
within the frame. In such cases we came to know that the element is within the frame.
Note: the most reliable approach is the second one i.e. checking weather the ancestor of the target
element is written inside i-frame tag.
Sachin M H
IV. If there is no nested frames then it will switch back to the default content area.
Window.ScrollTo():-
Select class:-
1. Select is a concrete class of selenium library.
2. It is use to handle dropdown list box.
3. There are 2 types of dropdowns:-
4. Single select list box
5. Multi select list box
6. Using non-static methods of select class we can handle both the type of list box.
7. It provides list of selection and deselection methods.
Sachin M H
Select class methods: -
1. getOptions().
2. Select by visibleTex().
3. Select by value()
4. Select by index()
5. Get first selectedOption()
6. isMultiple().
Select by visibleTex().
Signature : Public void select by visibleText(String args)
Usage:
1. Select select = new select (webElement)
2. Select select By visibleText(“Jan”);
• It is use to select the option in the list box.
• It receives the visible text as the argument.
• The argument is string type.
• The return type is void.
Select byValue()
Signature: Public void selectByValue(Stringargs)
Usage: Select select=new select(webElementele)
Select.scrollByValue(“7”);
• It is use to select the option in the dropdown listbox by using value attribute of the optionTag .
SelectByindex():
Signature: Public void selectByValue(intIndex)
Usage: Select select=new select(webElementele)
Select.scrollByValue(“7”);
• This Method is used to select the dropdown list option by using its index count. Here the index
value starts from zero.
• Every option Tag is assigned with index starts from zero.
• This method is use to select the option tag element based on its index value.
getFirstSelectedOption(): -
Signature: - Public WebElement getFirstSelectedOption()
Usage: - Select Select :- new select(webElementele).
webElement option = Select.getFIrstSelectedOption();
StringOptionText = option.getText();
Sachin M H
Select()
1. This method is use to confuse the default selected option from the dropdown listbox.
2. This method is most essential while checking the current selected option in the dropdown list since
it is directly synchronize with local system date and time.
getOptions()
public List<webElement> getOptions()
1. It will return the tagtext of the every available option tag within the select tag given to the select
object.
2. The return type is list of <WebElement>
3. We can use this method to verify all the options in the list box are correct or not and also they are
in the proper order or not.
isMultiple()
public Boolean isMultiple()
if(select isMultiple())
}else{
1. this method is used to check the type of the dropdown in the webpage.
2. It returns Boolean value, if it is true then the dropdown is multiSelect or else singleSelect type .
Sachin M H
Data Driven Testing:-
What is data driven testing..?
Read the data from external resource and run the test is called as data driven testing (parameterization
testing). It is always the best practice to store the data in the external files such as property file, Database,
excel sheet as Microsoft doc i.e., workbook, JASON file and XML file.
• In this we are fulfilling the obligations as a part of automation standard that in terms of not to
hardcode the data.
• This also helps us to create data driven testing environment that we call as data driven testing/
data driven frame work.
Sachin M H
Note:
1. properties file is light weight and faster execution compare to excel sheet (workbook).
2. Any data should not be hardcoded.
3. Test data should able to run in distant browser with minimal changes.
4. Test script data should get it from excels sheet.
5. Create a library method to read the data from excel and property file.
WorkBookFactory
AC
(I)
Create() WorkBook
(I)
getSheet() Sheet
(I)
getRow() Row
getCell()
(I)
cell
getStringCellValue()
getNumericCellValue()
setCellValue()
• Apache-POI is clam is open source library use to get and write data from all Microsoft documents
like excel, docs, ppt.
• In real time most of the company preferred to keep the test script data in excel, because data will
be in well organized manner, so that modification and maintenance is easier.
Installation steps: -
1. Go to the maven project.
2. Edit pom.xml file with the given dependency or else from the URL mentioned below.
https://mavenrepository.com.
3. Search for apache-poi.
4. Copy the dependency.
5. Add the dependency inside the <dependencies> in pom .xml.
Sachin M H
TestNG
What is TestNG..? or Why we should use TestNG..? or What are the advantages of the TestNG
in automation.? Or what if we don’t use TestNG in test automation..?
TestNG is a Java unit testing tool which is normally used by developers to perform unit testing (it is third
party tool used in selenium, and it is not developed by selenium developers). It is used in automation
because it provides lot of options to run the test-
o Generates reports.
o Batch execution.
o Parallel execution.
o Group execution.
o To add preconditions and post conditions.
o To perform parameterization and assertion.
o To add dependencies on test cases.
o To prioritize the test cases.
How to integrate TestNG in selenium or How to install TestNG and add it to the project in
eclipse.?
1. Open eclipse and click on and go to market place.
2. Search for testing in the filter section and click on install button.
3. Accept the license agreement and click on finish.
4. Press CTRL+N to get the wizard and search for testing folder for the conformation.
Go to maven repository https://mavenrepository.com and search for testNG.
5. Select the testNG from the list and choose the appropriate version i.e., 7.4.0.
6. After clicking on appropriate version click on the jar or .jar in the files section to download testNG
jar file.
7. Copy and paste, it into the jars folder of the java selenium project.
8. Right click on testNG.jar and click on build path and add to build path.
What is annotation..?
• Annotation is java template which is used to give information to the complier, developer and run -
time environment.
• Annotations can be used on top of variable, method or the class (if allowed)
Sachin M H
• Annotations values should always be constants or constant expressions.
What is @test..?
• @test is core annotation of testNG, without which we cannot run any testNG programs.
• Any method which is annotated with the @test is considered as a testcase and code returned
within this method is considered as testcase steps.
• Any class which contains at least one @test annotated method is called as testNG class.
• yes, we can run a testNG class without main method. testNG internally contains a main method
which will be called by the testNG plugin so we can run without main method.
How to run same testcase multiples time with the same test data in parallel execution..?
1. By using invocation count value and thread pool size value arguments for @test.
2. The test pool size attribute tells testNG to create a thread pool to run the test method here via
multi threads. With thread pool size, it will greatly decrease the running time of the test method .
How to run same testcase multiples time with the multiple test data in parallel execution..?
Sachin M H
Can we write multiples @test annotated method in a single testNG class..?
• Yes, we can write @Test annotated methods in a single class and in such cases the @Test
annotated method will execute in alphabetical order.
1. Yes, we should use the argument priority for @Test annotated method.
2. It accepts integer numbers.
3. 0, -ve, +ve numbers are also allowed.
4. The execution order will be from lowest no to the highest number.
5. If priorities are same then execution will be in alphabetical order.
6. Variables are not allowed.
How to execute other dependent @Test annotated methods before executing the current
@Test annotated methods..?
• We should use depends on method argument for the current @Test annotated method.
• In such cases the dependent @Test annotated methods will execute first.
• If dependent @Test annotated methods are passed then the current @Test annotated methods will
run.
• If the dependent @Test annotated methods are failed then the current @Test annotated method will
be skipped.
• We should use (enable =false) as an argument for test annotation annoted method
• Running Multiple testcase together for a single execution is called as Batch Execution
• To do batch execution we should follow below steps
o Select the testcase which has to be included into the batch execution In the package
o Rightclick >TestNG>convert to testNG > Finsh.(A testNG.xml ) will file will be created.
o Open the testNG.xml file > Rightclick (Run as test suite) all th selected testcase will run in
the order as mention in the .xml file.
<suite>
<test>
<classes>
<class>
Sachin M H
Explain the configuration to be done to run the same test case on multiple browers? Or Explain how
to perform cross browser testing using testNG ?
• We should use parameterization in the .xml file and the @test with the following below steps.
o Select the testcases in package and right click > TestNg > convert to TestNg > finish.
o In the testNG>xml File with in the <suite> create two test2 <test> having same <class>
names and name the <test> based on the browsername (eg) Chrometest & FireFoxTest.
o Add <parameter> for each <test> with name and value.
(Eg)
o In the java file we use the annotation called @parameters and receive the parameter from
xml file
(Eg)
@parameter(“browser”)
o Create the string argument for the test annotation annoted method to receive the value of the
parameter (“browser”)from the .xml file.
o While creating the string argument use @optional as a default value,so that if there is any
issue while reading the parameter this default can be used.
o Write the logic inside the @test annotated method to create the browser object based on the
received parameter using if else block.
Or
• Select the testNG classes to be executed in the parallel from the project in eclipse and rightclick
<testNG < ConverttotestNG < finish .
• On the TestNG .xml file Rightclick < RunAs < TestNG suite.
• Select the testcases to be executed on the multiple broswers in parallel from the project in eclipse
and rightclick < testNG < convertto testNG < Finish.
• In the testNG(.xml file) with in the <suite> create two <test> having same <class> name and name
the <test> based on the browser name for eg chrometest & Firefoxtest .
• Right click on the testNG(.xml file) > Run as> testNG suite.
Sachin M H
List & explain the configuration annotation of testNG ?
Or
1. @Before suite
This annotated method will execute at the time of testNG.xml suite execution.Any preconditions
common for the entire suite execution will be return here .
Eg – extent reports
2. @After suite
This annotated method will execute after the completion of testNG.xml suite execution .Any post
conditions common for thhe entire suite execution will be return here .
Eg -1.extent reports
3. @Before suite
This annoted method will execute of the time each testNG <class> execution (testNG class
execution).Any preconditions common for all test classes of the same class will be return here
Eg - open the broswers,
Maximize, implicity wait.
4. @AfterClasss
This annotated will execute after th completion of testNG class.Any post conditions like
minimize,Quit , etc, will done here .
5. @Before method
This annotated method will execute before each test case execution .Any pre condition like login
will be written here .
6. @After Method
This annotated method will execute after each test case execution .Any post condition like login will
be written here .
7. @Before test
This annotated method will execute at the time of (testing.xml) <test> execution.Any preconditions
common for the entire <test> while cross browser testing will be written here.
Sachin M H
8. @After test
This annotation will execute after the <test> execution .Any post conditions common for the <test>
while doing cross browser testing will be written here.
1) Before Suite
2) Before test
3) Before class
4) Before method
5) Test
6) After method
7) After class
8) After test
9) After suite
ASSERTIONS
What are Assertions ?
Assertions are basically the libraries (or) functions which are used to verify certain critical
checkpoints of the testcase.it is used to validate the testcase success upon expected and
actual outcomes.
It helps the programmer to lock failures based on the checkpoints in efficient way.
1. Assert ;
It has the static overloaded method called assertEquals(), through which we can assert any type
of data.
It is also called as hardassert because if there is any failure it will terminated the testcase by
reporting the assertion error.
2. SoftAssert:
It has the non static overloaded method called assertEquals(), through which we can assert any
type of data.
Here programmer should invoke a method called assertAll() to get all the assertions failures so
here programmer has a choice to choose when to get the assertions errors.
Sachin M H
3 Assertion errors will be shown Assertion error may (or) may not be shown
without fail depending on the ( assertAll() ) invocation.
4 All are Static methods here All are not static methods here.
POM is a Design Pattern and PageFactory is a class which is used within POM. We can say
PageFactory is a subset of POM.
PageFactory is a class which we will use to initialize the WebElements of the Page which are
created by using @FindBy Annotation. Otherwise we will get NullPointerException.
It has a static method called initiElements which will accept two inputs, one is the WebDriver
reference and another is the PageClassObject.
PageFactory.initElements(driver, pageObjectReference);
What is StaleElementReferenceException?
It’s one of selenium Execption , whenever webdriver try to identify an element , element was
available in GUI, but at time of performing an action on the elements element was not recognized due to
page got refreshed or elements may become old or element not attached to page in such case we get
staleElementReferenceException.
What Is POM? or
Page Object Model is a design Pattern which is used in Automation to write the test scripts
independent of the Element Identification. So here we write Java classes separately for test scripts and
WebElements. We have to follow a certain Procedure.
1. ) Create a Java Class for Each Page of the Application. Name the Java Class with the suffix Page like
LoginPage, HomePage etc…
Sachin M H
2.) Store the WebElements of Each WebPage into their own Page Classes. Like all LoginPage
WebElements should be stored in LoginPage.java class
4.) All the WebElements of Each class should be initialized with PageFactory.initElements() method.
5.) The Variables which holds the WebElement should be declared with private access level.
7.) Create a BasePage class and add all the common functionalities of all page classes in it. All the Page
classes should inherit it
8.) Create the Parameterized constructor in each Page class which accepts WebDriver Reference as input
and pass the same WebDriver reference to the BasePage Constructor using super() calling statement
9.) Create action methods to perform a full fledge Action like login, createCustomer, addProductToCart.
10.) In the Action method return the next LandingPage Object if the final outcome of the action method
redirects to next page.
Design Pattern means identifying the best solution for the frequently occurring problems in
development and Automation and using the same solution henceforth if the same problem is re -occurring.
Window Popup
This is a Popup which will open in the browser when the user wants to take the printout. This is an
OS level popup.
We cannot inspect this popup and there is no library method given in Selenium to handle it and also
we can’t avoid this popup. To handle it we should use Robot class.
This is a Popup which will appear whenever we are working with some gateway application and
only certain users are allowed to use this app. Or this popup will trigger whenever we are used the sites
behind proxy.
We cannot inspect this popup and there is no library method given in Selenium to handle it. So we
should find a trick to avoid it or we should use either Robot Class or AutoIT.
3.) It generally has username and password textboxes with ok and cancel button.
We should use the username and password in the URL itself. https://username:[email protected]
Notification Popup
This is a Popup which will open in the browser when we load it and used to take permission from the end
user for their website to show some notifications though the end user might not be on their Site. For
Example. Facebook, Gmail notifications will display though are not on it.
We cannot inspect this popup and there is no library method given in Selenium to handle it. So we should
find a trick to avoid it or we should use either Robot Class or AutoIT.
Sachin M H
How to avoid the Notification Popup?
a.) ChromeOptions is a concrete class and we should create the Object of it.
b.) Call the addArguments() method and use –disable– notifications flag as show below:
options.addArguments(“—disable—notifications”);
This is a Popup which will open whenever user needs to download some online content. It’s one of the
Operating System Level Popups.
We cannot inspect this popup and there is no library method given in Selenium to handle it. So we
should find a trick to avoid it or we should use either Robot Class or AutoIT.
• In Chrome We can disable the File Download Popup in browser settings by turning this option off
“Ask where to save each file before downloading” and then run the scripts.
• In Firefox We can disable the File Download Popup in browser settings by turning this option off
“Always ask you where to save files” and then run the scripts.
In Some rare scenarios we can’t avoid File Upload Popup. In Such cases we should use the Third
Party Tool AutoIT. Follow the below Steps:
Sachin M H
2. Open AutoIT Script Editor(like eclipse IDE) from C drive > programFiles(x86) > AutoIt3 > ScITE
> scite.exe (open this file).
3. Write the AutoIT Script in the scIte Editor (As discussed in class).
4. Save it as FileName.au3 extension in the Eclipse Project directory under AutoITScripts folder ( As
discussed in class).
5. Go to tools > Compile in Scite Editor. This step creates .exe file in the same location where you
stored.
6. Run that from the Java Program using exec() method of Runtime class of JDK as shown below
Runtime.getRuntime().exec(“./autoItPgms/fileupload.exe”).
This is a Popup which will open whenever user needs to upload a file. Generally clicking on an
upload button in the webpage generates this popup. It’s one of the Operating System Level Popups.
We cannot inspect this popup and there is no library method given in Selenium to handle it. So we
should find a trick to avoid it or we should use either Robot Class or AutoIT.
1.) We should check whether there is an input tag within the division of that file upload button (Generally
99% of the cases there will an input tag as shown below).
<input type=”file”>
In Some rare scenarios we can’t avoid File Upload Popup. In Such cases we should use the Third Party
Tool AutoIT.
Sachin M H
1.) Download and install AutoIT tool.
2.) Open AutoIT Script Editor(like eclipse IDE) from C drive > programFiles(x86) > AutoIt3 > SciTE>
scite.exe (open this file).
3.) Write the AutoIT Script in the scIte Editor (As discussed in class).
4.) Save it as FileName.au3 extension in the Eclipse Project directory under AutoITScripts folder (As
discussed in class).
5.) Go to tools > Compile in Scite Editor. This step creates .exe file in the same location where you stored.
6.) Run that from the Java Program using exec() method of Runtime class of JDK as shown below
Runtime.getRuntime().exec(“./autoItPgms/fileupload.exe”);
What is AutoIT?
It’s an open source GUI testing tool which was developed to automate Standalone apps in Windows.
It is a HLL programming Language and has a lot of Library methods through which we can
automate window App and it follows a VB Scripting like syntax.
It can be used in Selenium to handle The OS Level Popups like File Upload, File Download,
Authentication and Print Popup.
1. Go to https://www.autoitscript.com/site/autoit/downloads/
3. Then follow Next > ……. ……. Next > Next > finish
We can use it on only windows. It can’t be used on MAC PopUps or Linux PopUps. So we have to use
other Open Source Third Party tools which supports on MAC. Or Better is to Avoid this popup using
sendKeys() itself.
When the user opens a web page the main window is called as the parent browser window and other
browser windows which are opened with the parent window are called as Child browser popups or child
browser window popups.
We cannot inspect this popups. So we should follow solution give in the selenium WebDriver:
1.) Get the WindowID (A unique alphanumeric Identifier) of the child browser window on which you want
to perform action using getWindowHandle() or getWindowHandles() method and Store it.
Sachin M H
2.) Transfer the driver control to that child browser window using driver.switchTo().window(WindowID)
method.
3.) Identify the element/s using findElement() or findElements() method and perform desired actions.
How to handle Javascript popup and Explain all the methods of alert interface?
We Cannot inspect any JavaScript Popup so we have to use the library methods provided by
selenium WebDriver i.e. driver.switchTo().alert() to handle it.
driver.switchTo().alert() to handle it.
alert() is used to handle all the three types of JavaScript Popups. Whenever alert() is called it
perform two operations.
1.) Transfer the driver control to the current JavaScript Popup on the Web Browser.
In Selenium their is an Interface called Alert and it has 4 abstract methods, which are implemented
in the concrete class called RemoteAlert.
accept() _ This method is used to click on OK button of Javascript popup. The return type is void
and it …
The popup which is created using the html code is called as the hidden division popup.
Generally 70% of the hidden division popups are created using <div> tag.
1. Calendar Popups.
We can inspect any type of Hidden division popup so we can identify it by using findElement()
method and handle it normally like other web elements of the webpage.
Sachin M H
• We can use the same way how we handle other elements of the page. To select the dates we can take
the help of LocalDateTime class methods of java.time package.
• To select next month’s date on calendar we can use plusMonths(1) method and so on..
The popup which is created using JavaScript Language is called as JavaScript popup. There are
three types of JavaScript Popup.
Types Of Popups.
1.) Check whether we can inspect the popup. If the popup is inspect able then we can identify it by using
findElement and perform required actions on it.
2.) If popup is not inspect able then we should investigate whether any library method is provided within
Selenium WebDriver. If their perform actions on it using the library methods
3.) If popup is not inspect able and there are no library methods to handle it then we sh ould try to avoid the
popup using some tricks.
Sachin M H
4.) If we can’t inspect, no library methods provided and if we can’t avoid it then we should try Robot class
Methods to handle it.
5.) If we can’t inspect, no library methods provided, if we can’t avoid it and if Robot class methods are not
feasible then we should use open source Third party tools. One of them is AutoIT.
What is a popup?
Action Actions
• It's an Interface. • It's a concrete class.
• It has only one method i.e. perform() - void. • It is having multiple methods to
perform actions.
--------------------------------******************************----------------------------------------------
Sachin M H