Selenium Online-239 (1)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 133

Advantages of Automation:

i. It is faster & saves time.


ii. It reduces the human effort
iii. It is reusable
iv. Accurate & consistent

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.

Ex: Web application: Facebook, Google etc.

Client/Server: Skype, Gtalk, Whatsapp

Standalone: Calculator, Notepad, MS office.

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

2. Selenium RC (Remote Control)

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.

In order to do this while writing the code first we use "Upcasting"

Ex: WebDriver driver=new ChromeDriver();

SearchContext is super most interface which is extended by WebDriver interface.

Q. Explain the following statement:

ChromeDriver driver=new ChromeDriver ();

WebDriver driver=new ChromeDriver ();


i. WebDriver is an interface

ii. driver is reference variable

iii. = is assignment operator

iv. new is keyword

v. ChromeDriver is constructor

vi. ; is statement delimiter

REQUIRED SOFTWARE’S
1. JDK (Java Development Kit)

2. Eclipse

3. Browser

4. Selenium Jar file

5. Any web application

Downloading Selenium jar file:


Open the browser & go to the following website: www.selenium.dev/downloads and
download the selenium jar file

1. Go to required location example E: drive & create a folder with the name
Selenium247 or whatever name you want to give.

2. In Eclipse go to File > Switch Workspace > Other

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. Opening Firefox Browser

Q. Opening Edge Browser


Q. Opening Internet Explorer Browser

Q. How do you enter the URL in Selenium?


Q. What is the difference between get() and navigate() ?
Using get(), we can only enter the URL of the application whereas using navigate(), we
can enter the URL, move forward, move backward and refresh the webpage.

Q. How do you move back and forward and refresh the webpage?

Q. Closing the Browser


Q. What is the difference b/w close () & quit ()?

"close ()" will close only the current browser (main browser) where as "quit ()" will close
all the browsers of current WebDriver instance.

Q. How do you print title of the webpage?

Q. How do you get the page source of a webpage in Selenium?


Q. How do you maximize the browser in Selenium?

Q. How do you delete the cookies of the browser in Selenium?

Q. How do you print current URL of the webpage?


Q. How do you get and set the size of a browser in Selenium?

Q. How do you get and set the position of a browser in Selenium?


Q. Open google.com and verify whether the title is Google or not?
WebElement:
Anything present on the webpage is “WebElement”. Such as textbox, button, radio
button, dropdown list, error messages etc.

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).

Writing HTML Code:-

• Open the Notepad

• Write the following code & save it as Demo.html on the desktop or any drive.

<html>

<title> Selenium239 </title>

<body>

username : <input type="text">

password : <input type="password">

firstname : <input type="text">

surname : <input type="text">

<input type="checkbox"> keep me logged in

<input type="radio" name ="gender"> Male

<input type="radio" name ="gender"> Female

country code : <select name="code" single size=1>

<option> +91 </option>

<option> +1 </option>
<option> +852 </option>

<option> +33 </option>

</select>

mobile no : <input type="text">

email id : <input type="text">

address : <textarea> </textarea>

<input type="button" value="Save">

</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.

A WebElement generally contains 3 components:

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.

HOW TO SEE HTML CODE OF A WEBELEMENT IN CHROME?


- To see the source code of the element which is present on the web page, we right
click on the element and select ‘Inspect’ (Chrome & Firefox Browser).
Locators:
Locators are used to locate the web elements present in the webpage.

In selenium we have following 8 types of locators:

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:

WebDriver and WebElement are interface.

If the specified locator is duplicate (matching with multiple elements), then


findElement() returns address of first matching element.

If the specified locator is not matching with any of the element present on the page,
then findElement() will throw NoSuchElementException.

(Above concept is applicable to all the locators)

name Locator:
className Locator:

tagName Locator:
linkText Locator:
Note: the locator ‘linkText’ can be used only if the element is a link

(tag of the element should be <a>)


close() & quit()

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.

cssSelector has following syntax:

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.

The syntax is:

//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.

It has following syntax:

//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 ‘&nbsp’.

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.

It has following syntax :

1: //tag [contains(@AttributeName,’AttributeValue’)]

2: //tag [contains(text(), ‘textValue’)]


We can use contains function to handle dynamic elements (dynamic text or attribute
value) also.

Traversing in xpath
In xpath we can navigate from one element to another element which is called as
traversing.

Xpath supports two types of 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’.

Ex:- Download link of Java in Selenium website.

To use these kind of xpath we should perform following steps;

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

Important methods of WebElement:


i. sendKeys(): This method is used to type the input on textbox password field
& text area.
ii. click(): This method is used to click on any element such as button, link,
image, checkbox & radio button.
iii. clear(): This method is used to remove the text present in textbox,
password field or text area.
iv. getAttribute(): This method is used to get the property value of the
specified property name.
v. getText(): This method is used to get the text of the element.
vi. isDisplayed()- This method is used to check whether element is displayed or
not in the webpage
vii. isEnabled()-This method is used to check whether element is enabled or not
in the webpage
viii. isSelected()-This method is used to check whether element is selected or
not in the webpage
ix. getTagName()-This method is used to get the HTML tag of a webelement
x. getCssValue()- This method is used to get the css properties of a
webelement

Q. How do you remove the text present in the textbox?


Q. How do you replace the text present in the textfield or textbox?

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.

Q. Write a script to get the tag name of a webelement.


Q. What is the difference b/w getText() & getAttribute().

"getText()" is used to get the text of the element, where as "getAttribute()" is


used to get the property value specified property name.

Q. How do you retrieve the value present in the textfield or textbox?


Q. Write a script to copy the text present from one textfield & paste it another
textfield without using shortcut keys.
Q. Write a script to check whether the webelement is displayed, enabled and
selected or not in the webpage.

Q. Write a script to get the location of a WebElement


Q. Write a script to get the width and height of an image.

HANDLING MULTIPLE WEBELEMENTS:

In order to handle multiple elements we use findElements()which returns List of


WebElement [List<WebElement>]. List should be imported from java.util package.

Under the List we frequently use the following two methods.

1. list.size() - It returns no of elements present in the List (return type int)

2. list.get() – It returns element present in the specified index (return type


WebElement)

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.

Q. Write a script to select the checkboxes present on the page.


Q. What is the difference between ‘findElement()’ and ‘findElements()’?

findElement()

Return type is WebElement

If the specified locator is matching with Multiple elements, it returns first


matching element.

If the specified locator is not matching with any of the element then it will throw

NoSuchElementException.

findElements()

Return Type is List<WebElement>

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

Select class takes a parameterized constructor (single argument constructor) it takes


an argument type WebElement (address of the dropdownlist). In order to select the
required option present in the listbox we can use any one the following method of
Select class.

1. selectByVisibleText(str) > takes string argument

2. selectByIndex(int) > takes integer argument

3. selectByValue(str) > takes string argument

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

Q. Script to verify whether the listbox is single select or multi select


Q. Write a script to print all the options present in the listbox?

Q. Write a script to print all the selected options in the listbox?


getFirstSelectedOption()
It always selects the option which has a lower index value among the selected options.
Actions Class:
Using Actions class, we can handle mouse operations.

Actions class has parameterized constructor, which takes an argument of type


WebDriver.

If we call any method of Actions class, we must call perform( ) method.


Actions class is present in interactions package.

Q. How do you handle click operation?

Q. How do you double click operation?


Q. How do you handle context menu?

Right clicking is also called as Contextclick.

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?

Q. How do you perform “control and click” 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".

Ways to Achieve Synchronization:

1. Using sleep() of Thread class


2. Using “ImplicitlyWait”
3. Using ExplicitWait”

USING sleep() of THREAD CLASS


Thread.sleep( ) will always wait exactly for the duration specified. It will also
increases the number of lines of the code in the automation script.
To overcome this, we should use “implicit wait”. This option is given by ‘selenium’.
sleep() takes an argument as “millisecond”
USING IMPLICITLYWAIT:
If we use sleep() we should specify it in all the locations where application is slow. This
will increase the time taken to write script, it consumes lot of space and increases
maintenance of the script and it always waits for specified duration. Ex: if the duration
is 20 sec, it will always waits for 20 sec even though element is displayed in the 5 sec.

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

- DAYS - HOURS - MINUTES - SECONDS - MILLISECONDS - MICROSECONDS


– NANOSECONDS

If we use implicitlyWait() and if the element is not located then findElement() or


findElements() will keep on searching for the element after every 500
MILLISECONDS. This is duration is called as “Poling Period”

If the element is not located even after the duration then we get
NoSuchElementException.
Q. Explain the internal flow of implicitlyWait()?

Implicitly wait is used by findElement( ) or findElements( ) method,


During runtime, if the element is not present, it will be keep searching for the
specified element after every half second. This is called as ‘Poling Period’.
If the element is located, execution control goes to the next line.
If the element is not located even after the timeout, it will throw
NoSuchElementException.

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.

All the conditions are present in the class called ExpectedConditions.


Q. Explain the internal flow of ExplicitWait?

Here we should specify the waiting conditions explicitly.


The conditions are present in the class called Expected Conditions.
If the condition is satisfied, it will go to next statement.
If the condition is not satisfied, even after the specified duration, it will throw
‘TimeoutException’.

Q. What are the differences between ‘Implicitly’ and ‘Explicit’ wait?


Implicit:

We do not specify the condition

We can handle ‘findElement()’ and ‘findElements()’

After the duration we get ‘NoSuchElement’ exception

Duration can be DAYS, HOURS, MINUTES, SECONDS etc.

Explicit:

We should specify the waiting condition

We can handle any methods including ‘findElement()’ and ‘findElements()’

After the duration we get ‘Timeout’ exception

Duration will be only SECONDS

Handling Popups:
In selenium code to handle the pop up depends on the type of the popup.

The pop up can be categorized as:

i. Alert & Confirmation Popup


ii. Hidden Division Popup
iii. Calender Popup
iv. Web Push Notification Popup
v. File Upload Popup
vi. File Download Popup
vii. Child Browser Popup

Alert & Confirmation Popup:


Characteristics:

i. We cannot move these pop ups.

ii. We cannot inspect the pop up.

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.

In order to click on “OK” button we use “accept()” method.

In order to click on Cancel button we use “dismiss()” method of “alert interface”.

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:

i. We cannot move the pop up.


ii. We can inspect the pop up (it will be colourful).

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:

1. Popup will have minimize & maximize button.


2. We can inspect the popup.
3. We can move the popup.
4. Colourful.

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().

Window Handle will be always different and it will never be duplicate.


Q. Write a script to get the window handle and window handles of a browser.

Q. What is the difference between getWindowHandle( ) and


getWindowHandles( ) ?

getWindowHandle( ) :-

1. It returns window handle of current browser.


2. Return type is String.

getWindowHandles( ) :-

1. It returns window handle of all the browsers.


2. Return type is Set <String>.
Note:

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:

1. We cannot inspect the popup.


2. We can move the popup.
3. It will have 2 radio buttons.
i. Open with &
ii.Save file
4. It will have a checkbox.
(Do this automatically for files like this from now on).
File Upload popup:
Characteristics:

1. We can move the popup, but we cannot inspect it.

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(/).

Q. Write a script to upload a file in Naukri.com (Using Robot class)


Handling Frames :-

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

In order to come out of the frame, we can use:


1. driver.switchTo().defaultContent()
2. driver.switchTo().parentFrame()
3. driver.navigate().refresh()

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.

If frame id or name or index is incorrect, we get NoSuchFrameException.


Handling Chatbots in Selenium:
A chatbot is an AI (Artificial Intelligence) software/service that can simulate a
conversation or a chat with a user in natural language through messaging application.

Page Load Timeout in Selenium:


It focusses on the time a webpage needs to be loaded. If the page loads within the
time specified, then execution of script continues and if the page doesnot load within
the

timeout, we get TimeOutException (Default timeout is 30 sec).


Handling ToolTips :

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.

Tooltips were traditionally implemented as a 'title' attribute to an element. The value


of this attribute was shown as a tooltip on mouse-hover.

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.

Remove Chrome Warning in Selenium:


Kill Unused Windows Processes in Selenium:

Handling Insecure Websites in Selenium:

Adding Chrome Extensions in Selenium:


Verify Error Messages in Selenium:

Capture Chrome Log Files in Selenium:


A log file is just a simple file which keeps track of the record or event or information
when any event happens or any software run. This whole process is known as logging.
If we create a log file, we can track or debug our script easily if anything goes wrong in
the script (in case of failure).

Headless Browser Testing :


A headless browser is a web-browser without a graphical user interface. This program
will behave just like a browser but will not show any GUI.

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.

Why use a headless browser for test execution?


 Faster automation test execution: The performance with a headless browser is
better compared to real browser automation. The real browsers like Google Chrome,
Firefox, and Internet Explorer take a significant amount of time to load CSS,
JavaScript, Images, and open and render HTML. Headless browsers do not require
all this to load and will start performing functions without waiting for a page to load
completely. When we need to run the regression scripts, in headless browsers, we
could save time as there are much faster and can render results quickly.

 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.

Number of POM classes should be same as number of WebPages present in the


application.
1. Page Object Model is one of the java design pattern. It is used to develop and test
webpages.

2. In Page Object Model (POM), we declare the webelements using "FindBy annotation
(@FindBy)".

3. The syntax is :- @FindBy(locatorName="locatorValue")


private WebElement elementName;

4. We initialize the elements of POM class by calling "initElements()" method of


"PageFactory class".

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:

1. Page Object Model (POM) class.


-> Where we store elements and the methods.
-> It is also called as "Page Object Repository" or "Element Repository".
-> We cannot execute this class directly.

2. Test class.
-> It is used for execution purpose.
-> Execution happens by calling the methods present in POM class.

1. What happens if we don't use initElements() method ?


We get NullPointerException.

POM CLASS ACTITIME LOGIN PAGE:


TEST CLASS ACTITIME :

Q. How do you handle multiple elements in POM class ?


By changing type of element to List of WebElement (List<WebElement>)

Handling Multiple WebElements Using Page Object Model (POM):


POM CLASS GOOGLE AUTOSUGGESTION PAGE:
TEST CLASS GOOGLE AUTOSUGGESTION PAGE:
TestNG :-

TestNG is a unit testing framework. Using this we can execute multiple test classes and
we can also generate execution result.

NG - stands for NextGeneration.


TestNG class:-
1. It is a java class which has 'Test Method' instead of main method.
2. Any method developed using Test annotation(@Test) is called as Test Method.

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.

Q. Can we run multiple TestNG class together ?


Yes using TestNG Suite.
Note :-
-> TestNG suite is an XML file, which contains list of TestNG classes to be executed.
-> To create it, right click on the java project.
-> Go to TestNG.
-> Select convert to TestNG.
-> click Finish.
-> It creates testng.xml file inside java project folder.

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.

TEST CLASS ACTITIME LOGIN PAGE


TEST CLASS ACTITIME CREATE CUSTOMER PAGE

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.

If any test case is failed, it will be in red colour.


Q. How to execute only failed test cases/scripts?

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.

Q. How to skip the execution of a test class?

In TestNG , @Test(enabled=false) annotation is used to skip a test case if it is not


ready to test.

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

Q. Can we have multiple dependencies?


Yes i.e. when a test method is dependent on more than one test method
Q. If two methods dependant on each other & if we run the script, what happens?
We get TestNG exception.
This happens due to Cyclic Dependency
Verification in TestNG :-
Comparing actual result with expected result & reporting the status is called as
“Verification”.
In order to perform verification, we use Assert statements in TestNG.

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.

Q. What is the difference between Assert or HardAssert & SoftAssert or


Verify?
Assert :-
1. It will not execute remaining statements of current Test method, if
comparison fails.
2. All the methods are static.
3. We do not call assertAll(), because It immediately updates the result.

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:

@Test  indicates the Test Method of the class.

@BeforeMethod  This method will be executed before the execution of


every Test Method.

@AfterMethod  This method will be executed after the execution of every


Test Method.

@BeforeClass  This method will be executed before the execution


of the every current class.

@AfterClass  This method will be executed after the execution of the


every current class.

@BeforeTest  This method is executed before the execution of test


tag(<test>) present in testng.xml.

@AfterTest  This method is executed after the execution of test


tag(</test>) present in testng.xml.

@BeforeSuite  This method is executed before the execution of


suite tag(<suite>) present in testng.xml.

@AfterSuite  This method is executed after the execution of suite


tag(<suite>) present in testng.xml.

Execution Order of Annotations:

@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.

(Usage of the concept of inheritance in java)

Handling Excel File :-


1. While doing Functional testing, we test the components thoroughly (regularly)
with multiple inputs, which are derived using Test Case Design Techniques.
2. We store the data in Excel file.
3. To read the data from Excel file, we have API given by Apache called POI (Poor
Obfuscation (means Hiding) Implementation).
4. It can be downloaded from following URL ;
URL:- poi.apache.org/download.html
File:- poi-bin-3.17-20170915.zip
5. Extract the zip file.
6. It will create a folder with the name poi (version no).
Copy, paste all the 13 jar files of POI into java project and add them to
BuildPath.

Script to read data from a cell of an excel sheet:-


toString( ) method is overridden in Cell interface to return the value, instead of
address.

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.

Script to write data from a cell into an excel sheet:-


Automation Framework:-
It is the standard files & folder structures guidelines which should be followed by all
the automation engineers while automating the application.

It has 3 major stages:


1. Framework Design.
2. Framework Implementation.
3. Framework Execution.

We should use Automation Framework to have Consistency.

Framework Design :-

This is the initial stage where automation lead or manager specify rules, guidelines &
they will also create files and folder structures.

The framework is designed based on the experience & project need.


AutoConstant interface contains the data which does not change or should not be
changed. We store all the constants in this interface like storing the paths of
executable files.

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.

Framework is a collection of reusable components that makes automation development


and execution faster.

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.

To avoid repeating steps, we develop methods so it is called as Method Driven and to


test the application for multiple inputs we have used data driven.

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.

Interview Questions on Framework:

1. What is framework and why we use it?


2. What are the types of framework we have?
3. Which framework you have used in your project?
4. Explain the architecture of your framework?
ExplicitWait (Synchronisation) Using Selenium v4:

Verify Error Message using Assert class in Selenium:


Different Ways of Entering Character Sequence in Selenium:
MAVEN:

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.

So pom.xml file will contain the following dependencies:


Folder Structure of a Maven Project:

Whenever you are creating a maven project, two folders gets created

1. src/main/java
2. src/test/java

Under src/main/java, create two packages pom/pages and generics

Under src/test/java, create one package test/scripts

(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.

Right click on testng.xml file, select Run as TestNG suite.


Why We Used Maven Framework In Our Project:

 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:

1. No need to manually add the jar files in each project.


2. Creates a proper directory structure.
3. Easy to manage the dependency code

Open Bowsers Without Using Browser Drivers in Selenium:


Using WebDriverManager API.
Create a Maven project and add the dependency code i.e. webdriver manager.

How to Read Data from Properties File:


How to Read Data from Object Array :
How To Sort The Elements of a Dropdownlist :
How To Highlight The Elements of a Webpage :

Implementation in POM Class :

You might also like