0% found this document useful (0 votes)
16 views

Selenium Notes

The document discusses different operational methods and classes used for automation testing like dropdown, actions class, robot class, JavaScript executor etc. It provides details on how to handle different types of pop-ups during testing like alerts, notifications, hidden divisions. It also explains concepts like frames, handling multiple windows and taking screenshots. The key methods and their usage are explained for selecting and retrieving options from dropdowns, performing mouse and keyboard actions, executing JavaScript, switching between windows and frames.

Uploaded by

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

Selenium Notes

The document discusses different operational methods and classes used for automation testing like dropdown, actions class, robot class, JavaScript executor etc. It provides details on how to handle different types of pop-ups during testing like alerts, notifications, hidden divisions. It also explains concepts like frames, handling multiple windows and taking screenshots. The key methods and their usage are explained for selecting and retrieving options from dropdowns, performing mouse and keyboard actions, executing JavaScript, switching between windows and frames.

Uploaded by

pooja.hadpad1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

OPERATIONAL METHODS:

>>isMultiple(): boolean

it is used to identify dropdown belongs to the single select or multiselect

it will return true if the dropdown is multi select

it will return false if the dropdown is singl select

>>getOptions(): list<WebElement>

it is used to get all the options from dropdown

it will be work on single select and multi select also

Q. how to select options from dropdown without using selection method ?

for (int i =0;int i <=allOptions.size();i++)

if (allOptions.get(i).get(i).getText().equals("misalpaav"))

Thread.sleep(2000);

allOptions.get(i).click();

break;

>>getAllSelectedOptions():

it is used to get the options that we have selected from dropdown

to use this method it is mandatory to select the options from dropdown

>>getFirstSelectedOption():

It is used to get the first selected option from dropdown

It can be used on single select as well as multiple select

>>getWrappedElement():

It is used to get all the options from dropdown by considering as a single webelement

Return type is Webelement


//20 aug 2023

ACTIONS CLASS:

it is used to handle mouse actions

Actions class has total 21 method but we use only the methods that are used commonly required

it has 4 commonly used methods:

1. MouseHover = moveToElement(WebElement Target).perform()


2. DoubleClick= contextclick(WebElement Target).perform()
3. Right click=doubleclick(WebElement Target).perform()
4. DragandDrop=darganddrop(webelement src, webelement target).perform()

to access method of actions class we need to create object

Actions act=new Actions (WebDriver driver);

NOTE : TO PERFORM ACTIONS ON WEBELEMENT BY USING ACTIONS CLASS IT IS MANDATORY TO


CALL PERFORM()

PERFORM:

it is convinience method to perform mouse actions without calling build()

BUILD:

it is used to compile all the listed actions into single step

ROBOT CLASS : java package

It used to handle keyboard actions

All the methods of robot class are not static

To access method we need to create the object

It throws an exception i.e AWTEXCEPTION ( ABSTRACT WINDOW TOOLKIT )

It has two methods

1) to perform press actions: robot.KeyPress(KeyEvent.int KeyCode);

2) to perform release actions: robot.KeyRelease(KeyEvent.int KeyCode);

both the method is asking for argument i.e KeyEvent Class

Robot class belongs to java


TAKESCREENSHOT:<Interface>

There are the ways of calling getScreenshotAs()

WAY 1: directly create the Obj of Browserss Specific classes

ChromeDriver driver = new ChromeDriver();

driver.get ScreenshotAs();

WAY 2: upcast into remote web driver class

WebDriver driver= new ChromeDriver();

rwd. get ScreenshotAs();

WAY 3 : DownCast into RemoteWebDriver class

WebDriver driver= new ChromeDriver();

RemoteWebdriver rwd = RemoteWebdriver ()driver;

rwd. get ScreenshotAs();

WAY 4 : take a help of third party class i.e. EventFiringWebDriver(WebDriver driver)

WebDriver driver= new ChromeDriver();

EventFiringWebDriver ewf = new EventFiringWebDriver(driver);

ewf. get ScreenshotAs();

WAY 5 : Explicit TypeCast into TakeScreenShot();

WebDriver driver= new ChromeDriver();

TakeScreenShot ts =( TakeScreenShot)driver;

ts.ScreenshotAs();

Q. how to take a screenshot of webelement ?


24/08/23

HOW TO IMPLEMENT GETSCREENSHOT() ?

File src = ts.getScreenshotAs(OutputType.FILE);


File dest = new File("./Screenshot/instagram.jpg");

Files.copy(src, dest); //InputOutputException

JAVASCRIPT EXECUTOR

-Javascript executor is used to handle scrolling options such as scroll down, scroll up, scroll right,
scroll left as well as it is used to handle disable webelement, hidden webelement, generate a alert
pop up
-IT IS A INTERFACE
-It has two method
1. executeScript()
2. executeAsynScript()
-to call the method of java script executor we do explicit typecasting into java script executor

EX : WebDriver driver= new ChromeDriver();


JavaScriptExecutor jse = (JavaScriptExecutor)driver;
Jse.executeScript();
Jse.executeAsynScript();

25/08/23

Q. how to perform scrolling operations ?


To perform scrolling operation we need to execute some java scripts code into developers tool
(console)

Scroll down : window.scrollBy(0,500) …. //js code


Jse.executeScript(“window.scrollBy(0,500)”);

ScrollUp : window.scrollBy(0,-500) .…//js code


Jse.executeScript(“window.scrollBy(0,-500)”);

ScrollRight : window.scrollBy(5000,0) .…//js code


Jse.executeScript(“window.scrollBy(5000,0)”);

ScrollLeft : window.scrollBy(-5000,0) .…//js code


Jse.executeScript(“window.scrollBy(-5000,0)”);

Q. Scroll till particular webelement :

jse.executeAsyncScript("arguments[0].scrollIntoView(false)",newsElement);

27/08/23

FRAME :

if frame is not present in main page and we try to handle frame then we get NoSuchFrameException

How to switch control from frame to defaultPage?

driver.switchTo().defaultContent();

How to switch control from frame to parentPage ?

driver.switchTo().parentPage();
28/08/23

getWindowHandles() and getWindowHandle()

getWindowHandle()

it is used to get the address of parent browser or window

return type is string

getWindowHandles():

it is used to get the address of parent as well as child browser and window.

Return type is set of <string>

QUE.

1 how to close all browser ?

2 how to close all the browser without quit ?

3 how to close only parent window ?

4 how to close only child browser ?

5 how to perform maximize action on child browser ?

29/08/23

POP UP HANDLING

Pop up is a obstacle which occurs during execution of automation script

If pop up is there we need to handle by identifying it

Types of pop up :

A] WEB BASED POP UP

1. script pop up
- Alert
- Confirmation
2. Hidden division pop up
3. Notification pop up

B] WINDOW BASED POP UP

1. print pop up
2. file upload pop up

3. Download pop up

For window based pop up {autoit Download SCiTE editior}

1] SCRIPT POP UP

-CHARACTERISTICS ALERT POP UP:

it has only one button i.e OK

it is present in middle of the of the url bar

it is not inspectable

it is colorless

it is not movable

Que. How to handle alert pop up ?

To handle it we use switchTo()

Alert al=Driver.switchTo().alert().accept(); …//alert is a interface

al .dismiss();

al .getText();

al .sendKeys();

-CHARACTERISTICS OF CONFIRMATION POP UP:

It has two button i.e allow or deny

It is present in the middle of url bar

It is not movable

It is colorless

It is not inspectable

Que. How to handle confirmation pop up ?

We use switchT0();

Alert<I> al= driver.switchTo().alert();

al.accept();

al .dismiss();

al .getText();

NOTE : we cannot use sendKeys();


2] HIDDEN DIVISION POP UP :

It is not movable

It is colorful

It is present at middle of the webpages

It can be inspectable

Que. How to handle hidden division pop up ?

By inspecting pop up.

3] NOTFICATION POP UP:

It has 3 button i.e block, allow and cross symbol.

It is present at top left of url bar

It is colorless

It is not movable

It is not inspectable

Que. How to handle notification pop up ?

for notification pop up we handle according to browsers

that means if the pop up is there in Chrome or Firefox or Edge we need to create object of the
options class according to browsers.

Lets consider it is in Chrome,

ChromeOptions co = new ChromeOptions();

Co.addArguments(“—disable-notifications”);

WebDriver driver = new ChromeDriver(co);

Lets Consider it is in Firefox,

firefoxOptions co = new firefoxOptions();

Co.addArguments(“—disable-notifications”);

WebDriver driver = new firefoxDriver(co);

Lets consider it is in Edge,

edgeOptions co = new edgeOptions();


Co.addArguments(“—disable-notifications”);

WebDriver driver = new edgeDriver(co);

1/09/23

AUTOMATION FRAMEWORK

Automation framework is a set of rules and guidelines, files and folders, (standard folder templates)
That has to be followed by every automation test engineer to automate application.

OR

automation framework is collection of generic reusable methods which makes automation test
engineer life easy and achieve code efficiency

STAGES OF AUTOMATION FRAMEWORK :

1. Design … Any experience 5 to 6


2. Implementation ... Seniors 2.5 to 3
3. Execution … Freshers

Types of framework

Date Driven Framework

KeyWord Driven Framework

Modular Driven Framework

Method Driven Framework

TestNG

1] Date Driven Framework :

Storing the test data into external files such as excel , xml, .csv, property and data base ,fetch that
data through the generic reusable method and test the application is known as data driven
framework.

 Set up for Apache poi.jar


 Maintaining the Test Data in Excel Sheet
 Read the Test Data from Excel sheet

Why Data-Driven???
As a part of functional testing, we test each and every component of the
application with both valid and invalid data...
And since there will be many components, the test data is huge...
And if we hard-code test data then code size will be more...
Also difficult to maintain the test data...
Hence we keep it in external files and fetch them from there...
Why we prefer to store test data in Excel ???
1. Maintaining the test data in Excel is very Easy
(Adding, Modifying and deleting)
2. ALready Manual Test Engineers would have used excel to store
test data, So we just write generic reusable codes to fetch them.

To achieve Data Driven(read data) from excel Sheet,


We need to download Apache POI jars..
Steps:
1. Go to google, type 'Download Apache POI jars'
2. Click on first link(https://poi.apache.org/download.html)
3. Click on 'The latest stable release is Apache POI 4.1.2' link
4. Click on 'poi-bin-4.1.2-20200217.tar.gz (28.46 MB)' under Binary Distribution
5. Click on the first link...
6. Once Downloaded, uncompress and add all the jars to build Path
a. Right click on Project, go to build path-->Configure build path
b. Click on 'Libraries' tab
c. Click on 'Add External Jars'
d. Go to the Location where poi jars are downloaded and select all
the jars in poi-4.1.2 folder and also in 'lib','ooxml-lib'

To achieve data driven testing from excel sheet,


First we need to create an excel sheet and write our test data inside it...

Create a folder called 'data' under the project and create an excel under data folder
Right click on Project-->New-->Folder(name as 'data')
Right click on data folder-->Properties-->copy path-->open window explorer-->
paste it in the address bar...
Right click inside folder-->New-->Excel Sheet(name as inputData)

To read the data, we open the file in read mode,


we use POI libraries and guide our control to a particular cell and get the value in it

To read multiple data, use loop to get data one after another

To write the data, we open the file in read mode,


prepare the cell and once we write we open in write mode and save it...

2] KeywordDriven Framework

Storing the test data which is commonly or frequently used, as key-value pair
and reading it by using generic reusable method is known as KeywordDriven Framework

Here we store test data which we use very frequently like browserName,
url, valid username and password to login etc, in every test case
as key-value pair in property file and We use a java class called
'Properties' class and its method called getProperty to get the data.
getProperty() takes key as argument and returns its corresponding value

Creating property file in our project


1. Right click on the folder in which we want to create it ---> New ---> File
(name it as 'config' and give extension as .property or .properties)
2. Store test data in key-value pair as below

key value
browser Chrome
url https://www.actitime.com
username admin
password manager

StaleElementReferenceException
What is StaleElementReferenceException???
The Reference or Address of the element is old...

Why we get this exception?


When we use findElement()/findElements() to get the address of an element,
store it in a reference variable, but before performing action
if the webpage is refreshed, then on the webpage element's address will change,
but in reference variable we still have old address,
and we will be trying to perform action on the old address only.
Hence we get this exception

How to Handle it???


By Using Page Object Model(POM)

What is Page Object Model???


Page Object Model is one of the Java Design Patterns.
Mainly its an Object Repository which is used to store all the webElements
in one place. Hence it is also called Element Repository/Page Object Repository

How does POM handle StaleElementReferenceException???


In Page Object Model, we use @FindBy to get the address of the elements.
@FindBy will always get the new address/current address/latest address of the elements
therefore address will never become old. Hence we can avoid getting this exception

How do we Declare elements in POM class?


POM class means any class which contains @FindBy is known as POM Class..
In this class we declare by using @FindBy

Syntax: @FindBy(locatorName="locatorValue") AccessSpecifier ReturnType ElementName;


Example: @FindBy(id="username") private WebElement unTB;
How do we Initialize all the elements in POM class???
We use initElements() of PageFactory Class to initialize all the elements at once
initElements() gives instructions to all the elements(@FindBy) stored to fetch the address
and store it inside reference variable

initElements() takes two arguments


1. WebDriver reference variable
means browser class Object reference
example: driver
2. Object Page
means in which Class we have stored the elements
If the elements are in the same class/current class only
then we use 'this'
PageFactory.initElements(driver, this);
If the elements are in some other class,
Just create an object of that class and pass reference variable as argument
POMClass pc=new POMClass();
PageFactory.initElements(driver, pc);

Is User-Defined Constructor Compulsory to initialize elements???


No, but initializing the elements with initElements() is mandatory.
If not initialized then we get NullPointerException

How to handle multiple Elements in POM Class??


Use the return type as List<WebElement>

How do we do utilization in POM class???


By creating public 'getter' and 'setter' methods

Address returning method


public WebElement getUntb() {
return untb;
}

Action Performing Method


public void setUsername(String un) {
untb.sendKeys(un)
}

Uses of Page Object Model


1. It is used to store all the elements in one place. Hence it acts as
element Repository/Object Repository
2. It can avoid StaleElementReferenceException
3. Code Reusability is achieved, which increses the efficiency of
test Script development
4. Maintaining automation scripts is easy(Especially when requirements are
frequently changing)
5. Helps in encapsulating the elements
6. Can achieve abstraction
7. Can achieve method Driven testing

Method Driven Framework


Writing the implementation of the methods in different classes like generic classes
or POM class and calling the methods in test class
and executing the scripts by the help of these methods is known as
Method Driven Framework

Modular Framework:
For each and every module in the application we create a separate package
in the framework and we write all the test scripts related to
that module inside that package.

package Syntax: domain.ApplicationName.ModuleName

Modules In Our Fw-> PackageNames

TimeTrack com.actitime.timeTrack
Tasks com.actitime.tasks
Reports com.actitime.reports
Users com.actitime.users
Settings com.actitime.settings

There are 8 components in framework


1. Generic Library
2. Object Repository Library
3. Test Data
4. Resource
5. Test Script
6. Batch Runner
7. HTML Report
8. Screenshot

Explain your hybrid framework /


How to develop test scripts in our hybrid framework

There are few things which will never change throughout the whole project.
Such Constants I have stored inside IAutoConsts interface.
e.g., path of excel file and property file, key and value of the driver
executable files.

There are few things which are repeated like open browser, enter url,
verify loginPage and closeBrowser etc
These repeated actions I am storing inside a common class for all the
test scripts called as BaseTest, and I ensure that all the test scripts
extends this BaseTest.(Inheriting common properties from same place)

While automating the application, we require huge set of test data...


So we store it in data repo like excel sheets(Since easy to maintain data)
And we write generic reusable file handling libraries to handle data from them.

All the WebDriver related actions will be written in one place as


generic reusable libraries once and reused in testscripts whenever required.

All the elements on the webpage are stored in one place called object repo(POM)
wherein we declare, initialize and utilize the elements by writing public getters
setters and action methods.

In test scripts, we just call generic methods, getters, setters, action methods and
execute the automation scripts through these methods.(Test scripts become light weight)

Since We need to run all my scripts with one click We converted all the test scripts into
test suite(Batch executor) and run the suite.(testNG.xml file)

Finally we get HTML reports and screenshots of failed test cases

Where have you used Java concepts in your framework?

Inheritance: Commonly repeated actions we have stored in BaseTest and we


make sure every test class extends the BaseTest

Encapsulation and Abstraction: We use object repo to store the webelements


and we make the elements as private so as to encapsulate them within
the POM class, also we provide public getters and setters to
access them outside the class but cannot be modified..

Also here since we are hiding the functionality but just providing the
public getters and setters, hence we use abstraction concept

Polymorphism: While selecting the browser, in the BaseTest, we provide if-else condition
wherein depending upon the browser value it decides whether to
load ChromeDriver Object or FirefoxDriver object into the same reference
variable called driver.

Interface: In my framework, there were few things which were never changing like
key and value of the driver exe files and excel path and property path
To indicate these are constants, We have created an interface and
stored it inside it
Method Overloading: In WebDriverCommonLib Class, we write overloaded methods for
selecting an option from the dropdown

public void select(WebElement element, int index)


public void select(WebElement element, String text)
public void select(String value, WebElement element)

Method Overriding: In Listener implementation class called MyListener, we have


implemented the methods of ITestListener interface.
And all the methods are getting overridden inside MyListener class

Abstract Class: In BaseTest Class, though we have two methods, openBrowser() and
closeBrowser()[tearDown()] but they cannot run independently...
They are dependent on @Test methods for execution.
Since they cant run independently to denote that no automation engineer
should run BaseTest Class, We made BaseTest class as abstract class

Collection : While handling multiple elements we use List<WebElement> interface


Also in a situation of printing elements text without duplicate etc,
We use Set interface.. So List, Set are Collection topic

Array: To store the data in databanks we create an object of two dimensional array
in DataProvider concept...

static variable / Global public variable:

public static WebDriver driver;

In BaseTest, once we declare driver as WebDriver and make sure every test script
inherits and understands this declaration from BaseTest
Hence to access it everywhere, we declare as public.
To load this declaration first, before every other class wants to access it
we make it as static.
TestNG (7.8 version)

Testng is a framework and unit testing tool

It is a combination of j unit and n unit

J unit : Java unit

N unit : .net unit

It is supported by java and .net programming languageIit is developed by cedric Beust.

testNG is used to cover wider range of testing categories such as unit testing, functionality testing,
integration testing and end to end testing.

Q. HOW TO CREATE TESTNG CLASS ?

TestNG class is create inside the package same as java class.

In testNG class we cannot use main method

TestNG class should also contain annotations

Annotations should be followed by a methods

Ex : create a simple testNG class

Package: testNGPackage

Public class demo

@TestNG

Public void method1()

TestNG

indexNG class most of the time we use reporter.log(String args, Boolean args); as a printing

statement.

We are generating reports


ADVANTAGES OF TESTNG(7.8 version) OR FEATURES OF TESTNG :

1]TestNG generates reports in format of emailable-report.html and index.html

Q. HOW GENERTAE REPORTS

Once after testNG class is executed refresh the project

After refreshing the project we will get folder i.e test-output which contains testNG reports in
format of emailable-report.html and index.html

2]execution in testNG

With the help of testNG we can perform batch execution.

With the help of testNG we can perform parallel execution.

It can be perform by using classes, tests , methods.

Q. How to perform parallel execution ?

Select the testNG classes for which parallel execution is going to perform. Convert that classes into
testNG.xml suite file by selecting a parallel mode as classes/ test/methods.

Execute that testNG.xml suite file as a testNG suite so all the classes or tests / methods / started
executing at a same time.

That means parallel execution performed

By using parallel execution we execute multiple test cases at a same time and save the time of
execution also.

4]Q. with the help of testNG we can execute failed test Cases ?

-in a execution of testNG class or testNG.xml file if any method or test case got failed we can easily
track and execute that particular failed method or test case.

-for that we need to refresh the test output folder which has TestNG-failed.xml file

-this file has location of the failed test case or method

-if we execute that file as testNG suite it will execute only failed test case or method.

5] TestNG provides parameterization

Q. how to achieve parameterization in TestNG?

We can achieve parameterization for TestNG classes through the TestNG.xml suite file

For that in TestNG.xml file for that we must declare parameter tag with name and value attribute
Ex. <suite>

<test>

<parameter name= “browser” value=-”chrome”> </parameter>

To read that parameter into testNG class we must need to use @parameters annotation followed by
a @test annotation.

Ex. @parameters(“browser”)

@test

P v method(String browser)

That means whatever the parameters we have TestNG.xml file we pass to

That means we achieve data driven approach by using TestNG

NOTE : IN THIS CASE WE HAVE TO ONLY EXECUTE TESTNG FILE.

6] testNG provides annotations annotations are used to control the flow of methods

*sequence of annotations(imp)

5 @Test
4 BeforeMethod 6 AfterMethod
3 BeforeClass 7 AfterClass
2 BeforeTest 8 AfterTest
1 BeforeSuite 9 AfterSuite

@Test2
@Test 1
4 BeforeMethod 7 6 AfterMethod
3 BeforeClass AfterClass 10
2 BeforeTest AfterTest 11
1 BeforeSuite AfterSuite 12
7] testNG provides flags
Flags are used to control the flow of annotations or used along with the annotations
DESCRIPTION :
It is used to describe the annotation or method. It is asking for string values default values is empty
Q. How to use ?
> @Test(description = “Performs Login”)
P v method1()
ENABLED :
It is used to make the annotations or method as enables or disabled
It is asking for Boolean values
Default value is true
If the values is true that means test case is enabled and if it is false then it is disabled
Q. HOW TO USE ?
@Test (description =”perform login”,enabled =true)
P v method1()
{
}
@Test (description =”perform login”,enabled =false)
P v method2()
{
}
INVOCATION :
It is used to execute annotation or method for multiple time.
It acts like for loop.
It is asking for integers value
Default count of invocation is 1

PRIORITY :
It is used to execute the test case and annotations according to the priority given
It is asking for integer values
Default values is 0
Lesser priority higher execution
Same priority methods always be executing in alphabetical orders
Always negative priority will execute first if it is declared
DEPENDSONMETHOD :
It is used to make the methods depends on each other
It is asking for string[] array values.
Default value is empty

8]*with the help of testNG we can perform group execution


Q. how to perform group execution ?
For that we have to use groups flag in testNG class
We need to group the methods

FLAG NO.6 GROUPS :


It is used to group the annotation or test case
It is asking for string values
Default value is empty

ALWAYSRUN : FLAG NO 7
It is used to execute the method even if any previous method is failed or that are depend on each
other.
It acts like finally block of java
That means we use this flag along with methods that are important
It is asking for Boolean values default value is false

ASSERTION IN TESTNG / TESTNG PROVIDES ASSERTION :


Assertions is used to verify the features of an application
It is categorized into two types
1. hard assert
2. soft assert
HARD ASSERT :
IT IS used to verify critical feature of an application.
It the feature is not verified it will stop the execution of script
It is static
We can use hard assert with the class name as a reference
Ex. Asset.fail();
Assert.assertEquals(true,true);

(Imp) SOFT ASSERT :


It is used to verify non critical feature of an application
If it is verifying or not verified it will not stop the execution of script
We use soft assert with the object reference of soft assert
To make sure that which soft assert is not verified we always use assertall() at the end of script
Ex.. SoftAssert sa =new SoftAssert();
Sa.assertEquals(true,true)
9*] by using TestNG we can take screenshot dynamically- with the help of ITestListener interface.
____________________________________________________________________

BaseTest (class)
@BeforeMethod
SetUp()
Screenshot_of_failedmethod()

@AfterMethod
tearDown()
____________________________________________________________________
CustomListener extends BaseTest implements ITestListener
____________________________________________________________________

@Listener(CustomListener.class)
TestCase extends BaseTest
10*] TestNG provides data provider annotations which is used to achieve data driver approach.

Console o/p TestNG reports


Sysout Test-output TestNG Reports
Reporter.log(String s args) Emailable-report.html
Reporter.log(String , Boolean) Index.html

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy