Professional Documents
Culture Documents
Selenium Online-239 (1)
Selenium Online-239 (1)
Selenium Online-239 (1)
Limitations:
i. Initial investment is high.
ii. It requires constant maintenance
iii. Requires additional skill set
iv. 100% automation is not possible (It may be too costly or we may not have the
required technology).
Note: Because of above reasons we automate only long term projects, we automate
only repeating tasks (Regression testing).
Selenium:
It is a free & open source web application automation tool.
Note: 1. Free: In order to use selenium also we need not to purchase any license.
2. Open source: We can download the source code of selenium software itself so that
we can customize it according to our project need.
3. Web Application: Using selenium we can test only web application but not
client/server & standalone applications.
4. Automation tool: Selenium is used to test the application features, in this context
automation refers to simulation of manual testing steps & tool refers to a software
application.
Selenium Versions:
The Selenium tool has following major version.
1. Selenium IDE
3. Selenium WebDriver
4. Selenium Grid
Selenium IDE:
1. It has the simplest framework in the selenium suite.
2. Very easy to use and install.
3. Available only in Firefox as a plugin.
4. Execution is slow compared to RC and WebDriver.
5. No support for looping and conditional statements.
6. No programming knowledge is required.
Selenium RC:
1. First automation tool that allowed user to use a programming language like
JAVA, C#, Python, Ruby or Perl
2. Installation is complicated than IDE.
3. Needs RC server to be running.
4. Slower execution than WebDriver but faster than IDE.
5. Can perform looping and conditional statements.
Selenium WebDriver:
1. Does not readily supports new browsers
2. Communicates directly with the browser and does not need any RC server to be
running.
3. Faster execution than IDE and RC.
Selenium Grid:
It is a tool used to run parallel scripts across different machines and different
browsers at the same time.
Architecture of Selenium WebDriver:
Generally when we write a code in selenium we should ensure that the same code works
on different browser. This can be done using runtime polymorphism concept.
v. ChromeDriver is constructor
REQUIRED SOFTWARE’S
1. JDK (Java Development Kit)
2. Eclipse
3. Browser
1. Go to required location example E: drive & create a folder with the name
Selenium247 or whatever name you want to give.
3. Browse & select newly created folder and click on OK. It will restart the Eclipse.
4. Go to File > New > Project (Create a Java Project). Specify the name as
Automation and click Finish and Yes.
5. Right click on Java Project (i.e. Automation) and go to Build Path and select
Configure Build Path.
6. Click on Libraries tab and click on Add External jars and select the selenium jar file
that you have downloaded.
7. Right click on src, go to New > Package and give name as webdrivermethods
(Everything should be written in small case and click Finish)
8. Right click on the package and go to New >Class. Give any class name. Select public
static void main.
Q. Opening Chrome Browser
Q. How do you move back and forward and refresh the webpage?
"close ()" will close only the current browser (main browser) where as "quit ()" will close
all the browsers of current WebDriver instance.
Before performing the operation such as typing, clicking etc., first we should
make the selenium to identify the web element uniquely. In order to do this we use
"Locators" which is a property value or expression of the element. In order to specify
the property value or the expression we should have a basic knowledge of HTML.
HTML:
HTML stands for Hyper Text Markup Language which is basically used to create
webpages. We can also create GUI objects (Web Elements) using HTML DOM
(Document Object Model).
• Write the following code & save it as Demo.html on the desktop or any drive.
<html>
<body>
<option> +1 </option>
<option> +852 </option>
</select>
</body>
</html>
Double click html document file generated after saving the file, which will open the
webpage in the browser.
Note:
While writing the HTML code, use predefined keywords of HTML within angle brackets
(<>) which are called as HTML tags.
For starting tag there will be an ending tag indicated by forward slash (/). HTML tags
are not case sensitive & ending every tag is not mandatory.
1. HTML Tag: Any word which is present immediately after the less than symbol
(<).
2. Attributes: Any word or pair of words separated by "=" which are present after
the "html tag" till the greater than symbol (>) are called as Attributes also
called as Property name & Property value. Eg: type=”text”, type=”password” ….
3. Text: Any word which is present after the greater than (>) symbol of the "html
tag" till the end of the respective html tag are called as text of the element.
1. id
2. name
3. className
4. linkText
5. partialLinkText
6. tagName
7. cssSelector
8. xpath
All the above locators are available under "By" class of selenium. All of those are static
methods, all of them will take an argument of type "String.
We use "findElement" method to search the element present on the webpage based on
the specified locator & it returns an object of type "WebElement".
ID Locator:
If the specified locator is not matching with any of the element present on the page,
then findElement() will throw NoSuchElementException.
name Locator:
className Locator:
tagName Locator:
linkText Locator:
Note: the locator ‘linkText’ can be used only if the element is a link
partialLinkText Locator:
This locator is used to handle dynamic links.
How to get the Text of a WebElement:
StaleElementReferenceException:
Stale element means an old element or no longer available element.
This exception occurs when driver is trying to perform action on the element which is
no longer present may be because of page refresh and address change.
cssSelector Locator:
<html>
<body>
UN:<input type="text">
PW:<input type="password">
</body>
</html>
In the above sample page to identify the password field we can’t use id, name,
className,
linkText, partialLinkText because they are not present. We can use ‘tagName’ but it
has
duplicate user field. In this situation we can use cssSelector. CSS stands for
Cascading Style Sheets.
TagName[AttributeName=’AttributeValue’]
Note: We can use any attribute name and value present in the HTML code but it
should always show 1 matching element and highlight the element in the
application, then only write it down in the script.
xpath:
xpath is an unique path of an element in the HTML tree.
<html>
<body>
FN<input type="text">
LN<input type="text">
</body>
</html>
In the above sample web page we can’t use cssSelector because it is same as first name
field. In this case we can use ‘xpath’.
TYPES OF XPATH :
1. Absolute xpath
2. Relative xpath
3. Xpath by Attribute
4. Xpath by text()
5. Xpath by contains()
6. Traversing in xpath
7. Dependent Independent xpath
8. Xpath by group index
Absolute xpath
Specifying complete path of the element from the root till the element is called as
absolute xpath.
We write the xpath expression using / (forward slash). The first forward slash
represents beginning of the tree (root).
After every forward slash we should specify tag of immediate child element. We can
also use index which starts from 1.
If the index is not specified, it will try to identify all the matching elements.
Relative xpath
Absolute ‘xpath’ is very lengthy. In order to reduce the length of expression we can use
relative ‘xpath’.
In relative ‘xpath’ we use double forward slash (//) which represents any child.
xpath by Attribute
Relative xpath will reduce the length of the expression. But, it may not identify
required element even if we use index. Hence, to identify the required element we use
attribute also.
//TagName[@AttributeName= ’AttributeValue’]
xpath by text() function
If Attribute is matching with more than one element or if the attribute is not present
then we can identify the element using its text.
//tagname[text()=’textValue’] OR
//tagname[.=’textvalue’]
xpath by contains()
When we inspect the element, we cannot make out whether the space is given using the
spacebar or by using the key work or using the ‘ ’.
Even though we write the ‘xpath’ by copy pasting the value from the source code
displayed, it will not match with any element.
We can use contains function when there is a ‘Non Breakable Space’ to identify the
Element.
1: //tag [contains(@AttributeName,’AttributeValue’)]
Traversing in xpath
In xpath we can navigate from one element to another element which is called as
traversing.
1. Forward Traversing.
2. Backward Traversing.
Forward Traversing :-
Navigating from parent element to any of its child element is called as Forward
Traversing.
Backward Traversing :-
Navigating from child element to any of its parent element is called as Backward
Traversing.
Dependent- Independent xpath
In the application, some of the elements will be completely dynamic or duplicate. To
identify them we refer some other element, which is a static element and we use xpath
traversing to identify the dynamic element. This technique is called as ‘Independent
and Dependent xpath’.
1. For the given requirement, first inspect independent element (static element)
and note down its xpath.
2. Use backward traversing concept till it highlights both independent and
dependent element. It will be called as ‘Common Parent’, note down its path.
3. Now navigate from common parent to dependent element (dynamic element) and
note down its path.
4. Derive an xpath from independent element to common parent and then to
dependent element.
Xpath by Group Index
Q. Write a script to remove the value present in the textfield without using
clear().
Q. Write a script to copy the text present from one textfield & paste it another
textfield.
Q. Write a script to cut the text present from one textfield & paste it another
textfield.
Q. How do you login to the application without clicking on the login button ?
We can login to the application by pressing Enter Key after typing or entering
username & password instead of clicking on login button.
Note: For findElements() method we can use any of the 8 locators, but frequently used
is xpath.
Q. Write a script to print the text of the links present on the page.
findElement()
If the specified locator is not matching with any of the element then it will throw
NoSuchElementException.
findElements()
If the specified locator is matching with multiple elements it returns all the
matching elements.
If the specifies locator is not matching with any of the element it will not throw
any exception instead of this it returns EmptyList.
HANDLING AUTOSUGGESTION
Handling DropDownList
To handle the DROP DOWN LIST, we use Select class of selenium. It should be
imported from the following package:
import org.openqa.selenium.suport.ui.Select
If the specified option is duplicate it will select first matching option (in dropdown
list) and if the specified option is not present (text, value or index), we get
NoSuchElementException.
In Select class we also have the following 4 methods. This can be used on Multiselect
dropdownlist
1. deselectByVisibleText(str)
2. deselectByIndex(int)
3. deselectByValue(str)
4. deselectAll()
Single Select DropDownList
Multi Select DropDownList
UnsupportedOperationException
UnexpectedTagNameException
When we right click on any element we get list of options which is called as context
menu.
To right click on the element we use contextClick() method of Actions class and to
select required option in the contextmenu, we Robot class wherein we can use the
required keyboard operations.
Q. How do you move to a particular web element using actions class in selenium?
Q. How do you perform drag and drop operation using actions class in selenium?
Q. How do you perform “click hold and release” action in selenium?
Synchronization:
Process of matching speed of the selenium with the speed of application is called as
‘Synchronization’.
During runtime when selenium starts performing the operation on the application first
it will try to locate the element using the specified locator, if the element is found
then it will perform the operation, if the element is not found then it will throw
"NoSuchElementException ".
Most of the applications are very slow compared to the execution speed of selenium
because of this reason the automation script will fail. In order to overcome this we
should match the execution speed of selenium with the application which is called as
"Synchronization".
To overcome all these limitations, we should use the synchronization option given by
Selenium called implicitlyWait as shown below:
Syntax:
driver.manage().timeouts().implicitlyWait(Duration, TimeUnit);
We can write the above statement anywhere in the script, but as per selenium coding
standard, we write it in second statement.
The duration specified in implicitlyWait statement is used only by findElement() and
findElements(). But not by any other methods.
It takes two arguments first one is a duration and the 2nd argument is the TimeUnit
such as
If the element is not located even after the duration then we get
NoSuchElementException.
Q. Explain the internal flow of implicitlyWait()?
USING EXPLICITWAIT:
Whenever we can’t use implicitlyWait (Other than findElement() and findElement()) we
should use Explicit Wait. Since we specify the waiting condition explicitly it is called as
Explicit Wait.
When the control comes to wait.until statement it will keep checking the condition
after every 500 Mili Seconds. If the condition is satisfied it will go to next statement.
If the condition is not satisfied even after the duration we get TimeoutException.
Explicit:
Handling Popups:
In selenium code to handle the pop up depends on the type of the popup.
iii. It will have “OK” button (Alert) or “Cancel” button (Confirmation pop up).
Solutions:
In order to handle alert pop up first we should transfer the control from webpage to
the alert pop up, then we can use “getText()” method to get the message displayed on
the alert pop.
Once the alert pop up is closed, the control will be automatically transferred back to
the webpage.
Note:
Alert is an Interface.
If we try to perform action on alert or confirmation popup and the popup is not
present, then we get NoAlertPresentException.
If alert popup is displayed and if we try to perform action on any element present on
the page without closing the popup, then we get UnhandledAlertException.
NoAlertPresentException:
UnhandledAlertException:
Hidden Division pop up:
Characteristics:
Solution:
Since we can inspect it & it is part of html code we handle it using “findElement()”
method
Web Push Notification / Notification Popup:
Web push notification are messages that come from a website either to Allow or Block
the notification.
Calendar Popup:
Calendar pop up is also a type of hidden division pop up & to select the date which is
present on the calendar pop up, we use “findElement()” method itself.
Child Browser popup:
Characteristics:
Solutions:
To handle child browser popup we use driver.switchTo( ).window(w)
w – Window Handle of the browser
Window Handle :-
It is the unique alpha-numeric String of the window. To get window Handle of current
browser, we use getWindowHandle( ).
To get the window handle of all the browsers, we use getWindowHandles().
getWindowHandle( ) :-
getWindowHandles( ) :-
If you’re trying to perform operation on the window and the window itself is not
present or close, we get NoSuchWindowException.
File Download popup:
Characteristics:
Solutions:
To handle file upload popup we use "Robot class" where we specify complete path of the
file & we must use double backward slash(\\) & not the forward slash(/).
Before finding the element which is inside the frame, we should first switch to the
frame using:
1. Index of the frame
2. Id of the frame
3. Name of the frame
If you’re trying to perform any action on any webelement present inside the child
frame without switching to the frame, we get NoSuchElementException.
If you’re trying to switch from one child frame to another child frame, we get
NoSuchFrameException.
The tooltip is a text that appears when a mouse hovers over an object like a link, an
image, a button, text area, etc. in a web page. The text often gives more information
about the object on which it appears.
For accessing or verifying the static tooltips which are implemented using the HTML
"title" attribute, we can simply use the getAttribute("title") method of the
WebElement. The returned value of this method (which is the tooltip text) is compared
with an expected value for verification.
Click using JavascriptExecutor in Selenium:
Sometimes WebElement’s click() might not work even after using proper locator and we
might get ElementNotInteractableException / WebDriverException.
The reasons may be you need to upgrade/downgrade the respective browser driver or
maybe you need to change the selenium versions. It can be a compatibility issue.
Enter using JavascriptExecutor in Selenium:
Page Scrolling:
A Scrollbar is a lets you move around screen in horizontal or vertical direction if the
current page scroll does not fit the visible area of the screen. It is used to move the
window up and down.
Selenium WebDriver does not require scroll to perform actions as it performs auto
scrolling. But in certain web pages, elements only become visible once the user have
scrolled to them. In such cases scrolling may be necessary.
Scroll bar is of two types: Horizontal and Vertical scroll bar
To scroll using selenium, we can use JavaScriptExecutor interface that helps to
execute JavaScript methods through Selenium WebDriver.
We cannot create an object of an interface, so first we need to typecast it to
WebDriver driver object. And later we can call the method i.e. executeScript() to
perform the scrolling either horizontally or vertically.
In headless browsers, when Selenium tests run, they execute in the background.
Almost all modern browsers provide the capabilities to run them in a headless mode.
Multi-Tasking: Headless browsers can help you, multi-task. You can use your
browser or your machine to do anything else while the tests run in the background.
Save hours that we otherwise spend staring at the screen.
Handling Bootstrap Dropdown :
Page Object Model (POM) :-
Note :-
In Selenium, while automating the application, we develop two types of classes :- POM
& Test class.
2. In Page Object Model (POM), we declare the webelements using "FindBy annotation
(@FindBy)".
The syntax is :-
PageFactory.initElements(driver, Object Of POM Class);
NOTE :-
We cannot directly execute POM class, because we will never write main method in
class. We use different class for execution, which is called as "Test Class".
We develop two types of classes:
2. Test class.
-> It is used for execution purpose.
-> Execution happens by calling the methods present in POM class.
TestNG is a unit testing framework. Using this we can execute multiple test classes and
we can also generate execution result.
Note :-
When we execute test class, it automatically generates execution result in html
format.
To see it refresh the java projects, expand test-output folder. Right click on
emailable-report.html.
Go to 'open with' and select Web Browser.
Steps:
1. Create a java project and add selenium and testNG plugin to the project.
2. Inside src folder create two packages pom and test.
3. Inside pom package keep all your pom classes and test package keep all your
test classes.
There will not be any modifications in your POM classes, POM class remains as it
is.
Note:
Right click on the Java project, go to TestNG and select Convert to TestNG to
create the testng.xml file.
To execute it, right click on TestNG.xml.
-> Go to Run as.
-> select testNG Suite
TestNG Report:
To see the execution result of your test cases, first refresh the project, then a
test output folder will be created. Expand that test output folder, we will get a
file named as emailable-report.html. Right click on that file and click on Open
With-Web Browser.
Inside test output folder, we have a file called as testng-failed.xml (contains all
the test classes which has got failed). To run/execute all the failed test cases,
right click on that file and select Run As-TestNG suite.
Else we can comment the respective test class in the testng.xml file which you want to
skip.
Batch Execution:
Execution of the test cases one after another in the order in which the test classes
are present in the testing.xml file.
Parallel Execution:
Execution of the test cases parallely i.e. all at the same time.
Group Execution:
Executing the test cases present in the testNG suite as a group such as Regression
group or Smoke group.
To do group execution, do the following changes in your Test class and testNG.xml file
Q. Can we develop (have) more than one Test Method in the same class?
Yes.
Q. If TestNG class has multiple Test Method, on what basis (order) they are
executed?
Alphabetical order.
Q. How to execute the Test Method in required order?
Using priority.
Note:-
-Default priority is 0.
-We cannot use decimal numbers & variables to specify the priority value, but we can
use negative numbers.
-Execution order will be always in ascending order of the priority.
-If two methods have same priority, those two methods will be executed in alphabetical
order.
Q. How do you execute a Test Method multiple times?
Using InvocationCount
Note:-
- Default invocation count is 1.
- If invocation Count is less than or is equal to 0(zero), it will not execute respective
Test Method.
- Decimals & variables are not allowed.
Q. Can we use both priority and invocationCount?
Q. How do you execute a test method only when another test method is passed ?
Using dependsOnMethods
Scenario-1 :-
1. Open the browser.
2. Enter the URL of Actitime login page & verify the title of the login page
Note:-
During runtime if comparison fails, then Assert will not allow the TestNG to
execute remaining statements of current Test Method.Other methods are
executed as it is.
Note:
To continue the execution even after verification fails, we should use SoftAssert.
SoftAssert has all the methods of Assert class, but all are non-static.
Whenever we call methods of SoftAssert, at the end we must call assertAll() to
update the result.
Note :-
Any statements present after assertAll(), will not be executed, if comparison is failed.
SoftAssert :-
1. It will execute remaining statements of current Test method even if
comparison fails.
2. All the methods are non-static.
3. We should call assertAll(), to update the result.
Q. When do you use Assert & when do you use SoftAssert in your project ?
While verifying basic or critical features, we use Assert.
For other features we use SoftAssert.
Q. If you use both priority and dependsOnMethods, then which one is considered?
dependsOnMethods
Important Annotations of TestNG:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite
Usage of Above Annotations in Real Time:
Create a package with the name generics, inside that package create a class named
BaseTest.
Inside the BaseTest the following annotations are kept (varies from organization to
organization).
After writing the BaseTest, do the necessary changes in all your test class.
If sheet name, row index, or cell index is wrong then we get NullPointerException.
If the path of the excel file is wrong, we get FileNotFoundException.
If you’re trying to fetch integer value using getStringCellValue(), we get
IllegalStateException.
So we need to convert the integer value into string by putting a single quote (‘) before
writing the integer value.
Framework Design :-
This is the initial stage where automation lead or manager specify rules, guidelines &
they will also create files and folder structures.
BaseTest class contains the global data which is common for all the test scripts like
opening the browser, entering the URL, entering the UN and PWD, maximizing the
window, closing the browser etc.
ExcelLibrary class is used to read data from the excel file and is implemented using
Apache POI jar files. It can be reused in all the POM classes.
BasePage class contains reusable methods and it can be used in all the pom class
without remembering the syntax.
How to explain framework question in interview.
Based on the design, we can call the framework as Method Driven or Data Driven or
Hybrid Framework.
In our project, we have used combination of Method Driven and Data Driven, which we
call as Hybrid framework.
The framework is basically developed using TestNG, where for every test case we
develop a TestNG class with @Test (Test Annotation) and all the TestNG classes
extends BaseTest class (parent class).
Base Test is a super class which has two methods, @BeforeMethod and
@AfterMethod.
We use this super class to avoid the repetition of the code i.e. before every test, we
should open the application and after every test we should close the application.
Instead of writing this code in all the test classes, we write it in BaseTest class only
once and it is inherited in all the test classes.
When we run the TestNG class, first @BeforeMethod will be executed which opens the
browser and enters the URL.
After executing the @BeforeMethod, it will start the execution of test method
(@Test)
It will perform the action on the application by calling the required methods of the
POM class. All the POM classes extends BasePage class.
After executing the test method (@Test), it will execute @AfterMethod present in
BaseTest class and it closes the application.
After executing the automation scripts, it generates the result in HTML format
(emailable-report.html) inside ‘test-output’ folder of the project.
Based on the design, Framework is categorized into different types, such as:
1. Data Driven Automation Framework.
2. Method Driven Automation Framework.
3. Hybrid Driven Automation Framework.
Maven is a dependency tool i.e. instead of downloading the jar files and plugins manually
and configuring it with the project, we can do this automatically using MAVEN by
adding the dependency code inside pom.xml file.
Whenever you are creating a maven project, two folders gets created
1. src/main/java
2. src/test/java
(No changes will be there in your POM class and Test class)
To run the maven project, right click on the project, select testng and click on convert
to TestNG and click on Finish.
Using pom.xml (Maven) you can configure dependencies needed for building testing
and running code.
Maven automatically downloads the necessary files from the repository while
building the project.
Maven is also used to manage the dependencies. For example if you are using
selenium version 2.52.0 and any later point of time you have to use some other
version, then same can be managed easily by Maven.
Advantages of MAVEN: