Fourteen-May Lecture

You might also like

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

14-05-2021

search-htmlunit driver download


-open first link-htmlunit driver download
https://github.com/SeleniumHQ/htmlunit-driver/releases
-download first jar file-htmlunit-driver-2.49.1-jar-with-dependencies.jar
-Save it to selenium softwares
-without extracting configure with orangeHRM project bcz it's not ZIp it's jar file
-right click on launch create new class for LaunchHTMLUnit
>HtnlUnit Driver is very fast in nature
-type a code for same it didn't required set property bcz it's jar file, for jar
file we used set property
-run it

Navigation
Public static WebDriver driver;
driver.navigate().to("http://www.google.com");
-This navigate to given link

driver.navigate().forward();
-This navigate to next to google.com we should have to declare one mpre navigate to

driver.navigate().back();
-This navigate to back page i.e.google.com

driver.get(“http://www.google.com”);
-this work as navigate.to();

Assignment question
Have to give choice to user, which browser you want to open, give 4 options.

---------------------------------------15-may-2021------------------------
Login to webpage by selenium-

locators-a web page developed in HTML5


we locate a page by a property and property can be different so we have 8 diff
locators

create new package Locate Elements->class LoginElement

1. Locating webelements

Enter username Admin

Action webelement value

1. Enter username Admin


2. Enter password admin123
3. Click on Login button
4. Click on Welcome link
5. Click on Logout link

8 Locators are there in selenium webDriver


- By Id
- By name-this is the input name
- By className
- By partialLinkText-wherever the text is not constant we use this menthod for
partial constant text.
- By linkText-Text should be constant in this menthod
- By Xpath
- By CssSelector
- By tagname

click()-This mentod is also defined in webDriver to click on options,buttons.


sendKeys("Value")-This is used to send a value from code to web application

driver.findElement(By.id("txtUsername")).sendKeys("Admin");

Assignment No.2-

launch browser->open OrangeHrm->login-click on PIM->add employee->fname lname


->save-logout->close

What is Xpath?

Path is defined as XML path


It is a syntax or language for finding any element on the web page using XML path
expression i.e. using HTML DOM structure
XPath is used to find the location of any element on a webpage
Syntax
XPath contains the path of the element situated at the web page. Standard syntax
for creating XPath is.
Xpath=//tagname[@attribute='value']
// : Select current node
Tagname: Tagname of the particular node
@: Select attribute
Attribute: Attribute name of the node
Value : Valu

Value of the attribute


Types of Xpath
There are different types of Xpath
Absolute
It is the direct way to find the element
The key characteristic of XPath is that it begins with the single forward slash(/)
i.e. you can select the element from the root node
e.g on web page www.google.com Gmail hyperlink location is
/html/body/div/div[3]/div/div/div/div/div[1]/div[1]/a
If there are any changes made in the path of the element then that XPath gets
failed

Relative
The path starts from the middle of the HTML DOM structure
Its start with the double forward slash (//), which means it can search the element
anywhere at the webpage
e.g. on web page www.google.com Gmail hyperlink can be located with
//*[@id='gbw']/div/div/div[1]/div[1]/a
or
//a[@data-pid='23']
or
//a[contains(text(),'Gmail')]

notepad notes
- By Xpath
-> It stands for XML path
-> It is the path of DOM structure to locate your
element
-> 2 types
1. Absolute xpath [starts from the root node
i.e html . start with single slash /]
2. Relative Xpath [starts from the middle node and
it starts with double slash //]

"/html/body/div/div/div[10]/ul/li[3]/a"
//div[@id='divPassword']/input

17-05-2021
What is Alert?
Alert is a small message box which displays on-screen notification to give the user
some kind of information
Ask for permission to perform certain kind of operation
It may be also used for warning purpose

Types of Alerts
Simple Alert
Simple alert displays some information or warning on the screen
Prompt Alert
Prompt Alert asks some input from user
selenium webdriver can enter the text using sendkeys(" input…. ")
Confirmation Alert
Confirmation alert asks permission to do some type of operation

Moving on to Alert
import org.openqa.selenium.Alert;
Import this package prior to the script creation
This package references to the Alert class which is required to handle the web
based alerts
Alert alert=driver.switchTo().alert();
We create a reference variable for Alert class and references it to the alert
The above command is used to switch the control to the recently generated pop up
window

How to handle Alerts


Accept Alert
driver.switchTo().alert().accept();
The command accepts the alert thereby clicking on the Ok button
Dismiss Alert
driver.switchTo().alert().dismiss();
The command closes the alert thereby clicking on the Cancel button and hence the
operation should not proceed
Get Alert message
driver.switchTo().alert().getText();
Send data to Alert box
driver.switchTo().alert().sendKeys("Text");
notepad notes

How to handle Alerts


Accept Alert
driver.switchTo().alert().accept();
The command accepts the alert thereby clicking on the Ok button
Dismiss Alert
driver.switchTo().alert().dismiss();
The command closes the alert thereby clicking on the Cancel button and hence the
operation should not proceed
Get Alert message
driver.switchTo().alert().getText();
Send data to Alert box
driver.switchTo().alert().sendKeys("Text");

3. Handling Alerts
- Use Alert class. It contains methods for
handling the alert.
- Alert alert = driver.switchTo().alert();
- Get the message on Alert
alert.getText();
- To click on OK button
alert.accept();
- To click Cancel button on alert
alert.dismiss();
- To send text on alert
alert.sendKeys();

19-05-21

What is checkpoint?
Checkpoint compares the expected values of object properties to the object's
current values captured at runtime

Various ways to compare


Single line text can be taken using getText() method
Checking presence of particular word in entire page using getPageSource() and
contains()
Comparing entire page
Storing page contents at runtime in a file and comparing it with expected contents
stored in a file
notepad notes
1. Checkpoints
- Checkpoints are used to check the expected
output for any test
- Text checkpoints
-> Single line text
-> Single word
-> compare 2 text files
assignment-
You have to login into orangehrm and capture contents of dashboard page and then
compare with expected

20-5-21
Various ways to compare
Comparing two screen shots of entire Page
Comparing two images
Taking screenshot of full page
TakesScreenshot indicates a driver to capture a screenshot and store it in
different ways
OutputType can be
File
Bytes
Base64
Class
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("PageScreenshotActual.png"));
Comparing 2 images
Toolkit object is an abstract class that provides an interface to platform-specific
details
The getDefaultToolkit() method returns the system’s default Toolkit object.
Toolkit.getDefaultToolkit().getImage(file1)
GetImage - Returns an image which gets pixel data from a specified file
The PixelGrabber class implements an ImageConsumer which can be attached to an
Image to retrieve a subset of the pixels in that image

public PixelGrabber(Image img, int x, int y, int w, int h, boolean forceRGB)


img - the image to retrieve the image data from
x - the x coordinate of the upper left corner of the rectangle of pixels to
retrieve from the image
y - the y coordinate of the upper left corner of the rectangle of pixels to
retrieve from the image
w - the width of the rectangle of pixels to retrieve, -1 if not known
h - the height of the rectangle of pixels to retrieve, -1 if not known
forceRGB - true if the pixels shou
true if the pixels should always be converted to the default RGB ColorModel
Manali Kulkarni13:38
getPixels()
Grab all the pixels in an image and return the result as an array
Currently the file formats supported are PNG, JPEG, GIF
PixelGrabber grab1 =new PixelGrabber(image1, 0, 0, -1, -1, false);
int[] data1 = null;
if (grab1.grabPixels()) {
int width = grab1.getWidth(); // findling width in number of pixels
int height = grab1.getHeight(); // finding height in number of pixels
data1 = new int[width * height]; // declaring dimentions of int array
data1

Finding location of Image on Page-


WebElement glogo = driver.findElement(By.xpath(".//*[@id='hplogo']"));
Point point = glogo.getLocation();
int gWidth = glogo.getSize().getWidth();
int gHeight = glogo.getSize().getHeight();
The Point class represents a location in a two-dimensional (x, y) coordinate
To perform the image read, write operation use ImageIO class
public BufferedImage getSubimage(int x, int y, int w, int h)
x - the X coordinate of the upper-left corner of the specified rectangular region
y - the Y coordinate of the upper-left corner of the specified rectangular region
w - the width of the specified rectangular region
h - the height of the specified rectangular region
Returns a subimage defined by a specified rectangular region

Have to login by admin go to skill page and add skill and after that take
screenshot and compare with expected. crop the image which skill you have added

21-05-21
What is Alert?
Alert is a small message box which displays on-screen notification to
give the user some kind of information
Ask for permission to perform certain kind of operation
It may be also used for warning purpose

Types of Alerts
Simple Alert
Simple alert displays some information or warning on the screen
Prompt Alert
Prompt Alert asks some input from user
selenium webdriver can enter the text using sendkeys(" input…. ")
Confirmation Alert
Confirmation alert asks permission to do some type of operation

Moving on to Alert
import org.openqa.selenium.Alert;
Import this package prior to the script creation
This package references to the Alert class which is required to handle the web
based alerts
Alert alert=driver.switchTo().alert();
We create a reference variable for Alert class and references it to the alert
The above command is used to switch the control to the recently generated pop up
window
How to handle Alerts
Accept Alert
driver.switchTo().alert().accept();
The command accepts the alert thereby clicking on the Ok button
Dismiss Alert
driver.switchTo().alert().dismiss();
The command closes the alert thereby clicking on the Cancel button and hence the
operation should not proceed
Get Alert message
driver.switchTo().alert().getText();
Send data to Alert box
driver.switchTo().alert().sendKeys("Text");

notepad notes
1. What are Alerts?
- Alert is a message box that contains some
information with an ok button.

2. Types of Alerts
- Simple Alert
- Confirmation Alert
- Prompt Alert
- Simple Alert
-> It is a message box with an OK button.

- Confirmation Alert
-> It is an alert which confirms your action,
and has 2 buttons , OK and Cancel

- Prompt Alert
-> It is an alert which accepts input from
user.
3. Handling Alerts
- Use Alert class. It contains methods for
handling the alert.
- Alert alert = driver.switchTo().alert();
- Get the message on Alert
alert.getText();
- To click on OK button
alert.accept();
- To click Cancel button on alert
alert.dismiss();
- To send text on alert
alert.sendKeys();

How to handle multiple popups


When we have multiple windows in any web application, the activity may need to
switch control among several window from one to other in order to complete the
operation
After completion of the operation, it has to return to the main window i.e. parent
window.
driver.getWindowHandles()
To handle all opened windows by web driver, we can use "Driver.getWindowHandles()"
and then we can switch window from one window to another in a web application
Its return type is Iterator<String>
driver.getWindowH
Its return type is Iterator<String>
driver.getWindowHandle();
When the site opens, we need to handle the main window by driver.getWindowHandle()
This will handle the current window that uniquely identifies it within this driver
instance. Its return type is String
Closing Multiple popups
Set<String> handles= driver.getWindowHandles();
for(String handle : handles)
{
System.out.print(driver.switchTo().window(handle).getTitle());
driver.switchTo().window(handlelt).close();
}

Login by admin and add one skill manualy and you have to delete and handle pop up

Assignment
1
1. Single cell
2. Column headings
3. All names from table
4. all rows and count for number of rows

2.Search a particulare name inside table and if it present show the position or
else not present
24-05-2021
Frames-we can't directly switch frame to frame we should get back to parentframe
or default content first then switch to another frame.

Switching to other frames


IFrame Is another web element and user can not locate Its element directly
switchTo.frame(int frameNumber)
Pass the frame index and driver will switch to that frame
to switch to 0th iframe use
driver.switchTo().frame(0)
switchTo.frame(string frameNameOrId)
Pass the frame ID or frame Name and driver will switch to that frame
To switch to iframe whose name is iframe1
driver.switchTo().frame(“iframe1”)
switchTo.frame(WebElement frameElement)
Pass the frame web element and driv
Pass the frame web element and driver will switch to that frame
WebElement iframeElement = driver.findElement(By.id("IF1"));
driver.switchTo().frame(iframeElement);
switching back
To Switch back using
driver.switchTo().defaultContent();
Or
Driver.switchTo().parentFrame();

1. Handling drop downs


- Use Select class
- Methods
-> selectByIndex
-> selectByValue
-> selectByVisibleText

Keyboard and mouse movements


Handling special keyboard and mouse events are done using the Advanced User
Interactions API
It contains the Actions and the Action classes that are needed when executing these
events
Import the Actions and Action classes
import org.openqa.selenium.interactions.action;
import org.openqa.selenium.interactions.actions;

Methods
build()
Generates a composite action containing all actions so far, ready to be performed
(and resets the internal builder state, so subsequent calls to build() will contain
fresh sequences)
clickAndHold()
Clicks (without releasing) at the current mouse location.
.
doubleClick()
Performs a double-click at the current mouse location.

dragAndDrop(WebElement source, WebElement target)


A convenience method that performs click-and-hold at the location of the source
element, moves to the location of the target element, then releases the mouse
keyDown(Keys theKey)
Performs a modifier key press
keyUp(Keys theKey)
Performs a modifier key release
moveToElement(WebElement toElement)
Moves the mouse to the middle of the element

perform()
A convenience method for performing the actions without calling build() first
release()
Releases the depressed left mouse button at the current mouse location
sendKeys(java.lang.CharSequence... keysToSend)
Sends keys to the active element
sendKeys(WebElement element, java.lang.CharSequence... keysToSend)
Equivalent to calling: Actions.click(element).sendKeys(keysToSend)

Method 1:
act.clickAndHold(From).build().perform();
act.moveToElement(To).build().perform();
act.release(To).build().perform();
Method 2:
dragAndDrop(Source, Target).build().perform();

25-05-2021

What is Data Driven Testing?


Executing same test again and again with different sets of data is called Data
Driven Testing
Advantages of Data Driven Testing
Hard coding of data from the script is removed
Data is taken from a external file
Bulk data can be added to database

BufferedReader
BufferedReader class reads text from a character-input stream, buffering characters
so as to provide for the efficient reading of characters, arrays, and lines
String readLine()
This method reads a line of text
import java.io.BufferedReader;

BufferedWriter
The Java.io.BufferedWriter class writes text to a character-output stream,
buffering characters so as to provide for the efficient writing of single
characters, arrays, and strings
import java.io.BufferedWriter;

FileWriter
This class inherits from the OutputStreamWriter class
The class is used for writing streams of characters
import java.io.FileWriter;

FileReader
Class for reading character files
import java.io.FileReader;
BufferedReader br = new BufferedReader( new FileReader("datafile.csv"));
while((line=br.readLine())!=null)
{
String[] data=line.split(",");
driver.findElement(By.xpath(“”)).sendKeys(data[0]);
driver.findElement(By.xpath(“”)).sendKeys(data[1]);
}

Assignment-
edit skill= write script for editing skill and add skill manually one, add that
skill and description and enter on orange hrm using csv file and object repositery

31-05-2021
TestNG is a testing framework inspired from JUnit and NUnit but introducing some
new functionalities that make it more powerful and easier to use
Selenium tests do not generate the Test Results in proper format
Hence user use TestNG for grouping test cases, parallel testing and getting
meaningful test reports

TestNG Annotations
@Test
The annotated method is a part of a test case
@BeforeMethod
The annotated method will be run before each test method
@AfterMethod
The annotated method will be run after each test method
@BeforeClass
The annotated method will be run before the first test method in the current class
is invoked
@AfterClass
The annotated method will be run after all the test methods in the current class
have been run
@BeforeTest
The annotated method will be run before any test method belonging to the classes
inside the tag is run
@AfterTest
The annotated method will be run after all the test methods belonging to the
classes inside the tag have run
@BeforeSuite
The annotated method will be run before all tests in this suite have run
@AfterSuite
The annotated method will be run after all tests in this suite have run
Annotations execution
Testsuit
Test
Class
Method
Test
Method
Class
Test
Testsuit

01-06-2021

Cronological order
BeforeTest
BeforeMethod
Test
AfterMethod
BeforeMethod
Test2
AfterMethod
AfterTest

Multiple @Test annotation


We can have multiple @Test annotations in a single TestNG file
By default, methods annotated by @Test are executed alphabetically
Methods can be executed in a different order, by using parameter "priority"
@Test(priority=0)
TestNG will execute the @Test annotation with the lowest priority value up to the
largest

Dependent Tests
TestNG allows to specify dependencies with attributes dependsOnMethods
@Test(dependsOnMethods={'openBrowser'})
public void closeBrowser()
{ driver.close();
}
@Test
Public void openBrowser()
{ driver = new FirefoxDriver();
}

whenever we include groups that time alwayRun=true is used to run before and after
methods

03-06-2021
What is POM?
Page Object Model is a design pattern to create Object Repository for web UI
elements
Under this model, for each web page in the application there should be
corresponding page class
Page class will find the WebElements of that web page and also contains Page
methods which perform operations on those WebElements

Advantages of POM
In Page Object Model, operations and flows in the UI is separated from verification
This concept makes our code cleaner and easy to understand
Object repository is independent of testcases, so we can use the same object
repository for a different purpose with different tools
We can integrate POM with TestNG/JUnit for functional testing and at the same time
with JBehave/Cucumber for acceptance testing
Code becomes less and gets optimized because of the reusable page methods in the
POM classes.
Me
Methods get more realistic names which can be easily mapped with the operation
happening in UI
POM Structure
Configuration
Contain configuration parameters like browser name, applicaiton url etc
Driver class will have main method which calls various methods from specs
Common
Contain common methods
Specs
Contain methods which operate on UI elements
Pages
Will maintain object repository of all objects on respective Web Pages of AUT
Test data
Will contain all test data sheets to be used

pacakge-POM.TESTDATA
inside New file loginData.csv
enter Admin and admin123

You might also like