Selenium
Selenium
-----
Whole Architecture of Testing
-------------------------------------------------------------------------
-----
Manual Testing
|
Automation Testing
(Selenium)
|
Frame Works
(Keyword Driven)
(Data Driven)
(Hybrid)
|
TestNg Framework
|
Ant and Maven
|
Jenkins for CI
(Continous Integration)
-------------------------------------------------------------------------
-----
Defect Tools :
*************************************************************************
******
Why we need automation testing ?
*************************************************************************
******
There are some category of test cases that are not suitable for
automation
- Test cases newly designed and not executed manually atleast once
- Test cases for which requirements are changing frequently
- Test cases which are executed on ad-hoc basis. Because of adhoc
testing doesn't
have test cases.
During maintenance new functionalities are added to the system under test
with
successive cycles, automation scripts need to be added, reviewed and
maintain
for each release cycle. Maintenance becomes necessary to improve
effectiveness
of automation scripts.
*************************************************************************
*****
What is Selenium ?
*************************************************************************
*****
Selenium is suite of software tools to automate webbrowser applications.
It is
not of single tool it is collection of tools like silk test,QTP etc. It
is only
used for web based applications it will be not applicable for Desktop
application,
windows based client server applications. It is an open source suite of
tools
mainly used for function and regression test automation. Selenium
supports more
operating environments like Linux, Ms windows, macintosh etc. Selenium
supports
various browsers like chromium, firefox, IE etc. Selenium IDE supports
only firefox
browser. Selenium grid is used for test execution. It supports atleast 6
programming
languages like java, python, C#, Ruby,PHP and perl to write test scripts.
*************************************************************************
******
Why selenium is preferred over other ?
*************************************************************************
******
*************************************************************************
******
Other tools like selenium ?
*************************************************************************
******
There are other tools that are available in market like selenium. But the
fact is
they are limited to various factors like programming language, brower
support,
operating system support etc. Among them QTP is one of the conquer in the
testing
market. Apart from QTP, selenium there is other tool that looks similar
to selenium
is protractor which stands next in the market after selenium.
*************************************************************************
******
History of Selenium ?
*************************************************************************
******
*************************************************************************
******
Difference between Selenium RC, Selenium IDE, Selenium Grid & Selenium
Webdriver ?
*************************************************************************
******
As we say selenium is set of tools used for automating the web browser.
It has
-Selenium IDE
-Selenium RC
-Selenium Webdriver
-Selenium Grid
Editor is place where we write our code in seleniss which supports it.
Application
we need to test on web browser. To automate the website under test.
Between our
code and application there is proxy server called as selnium RC server.
When
ever we run the code first it will go to proxy server. Basically we use
selenis
commands to automate the application. First selenis commands are go to
server.
RC server interpret the selenis commands we send then it will trigger
particular
java script event on the application. Underlying java script is used to
trigger
the events in the application. With this events triggering the automation
will
happens in application. Day by day browsers are becoming more robust
because of
that they are not allowing to trigger java scripts on application. There
may be
security issues, and lot of issues so web browser used mechanism not to
trigger
java script events on their browser. Applications are facing many
inconsistency
to run. The API's for RC not supporting rich API's like ajax,html, mouse
events.
The main drawback is java script triggering on application. So due to
these issue
they officially depreciated and made new version which is successor of
selenium
RC with the name called Selenium Webdriver.
- Selenium WebDriver :
----------------------
It is successor of selenium RC. There is direect interaction between
editor and
application under test. There is not RC server in between which makes
webdriver
more powerful among all tools. It is programming interface (with no IDE)
to
create and execute test cases. If the broswer doesn't support java script
then
webdriver handles this issue by interacting the browser in its native
language.
webdriver uses browser native language to host the application. If we use
browser
own language then it is easy to trigger any event on the application.
Webdriver
handles it smartly, it will interact with application using browser
native language.
With this it overcomes the issue of selenium RC.
- Selenium Grid :
----------------
It is test execution design only but not used for test case design.
Primary purpose
of selenium grid is parallel testing/cross browser testing. Selenium grid
executes
test cases across multiple browsers, operating environments and machines
in
parallel. In other words executing test case at once on different
combination
of OS and browsers.
-------
Node 1 <------- | HUB | ------> Node 2
-------
|
|
Node 3
EX :
DesiredCapabilities capability = DesiredCapabilities.firefox();
// DesiredCapabilities class is used to set the browser we want to run on
the
// node
capability.setCapability(FirefoxDriver.BINARY, new File("C:\\Program
Files (x86)\\Mozilla Firefox\\firefox.exe").getAbsolutePath());
// We are setting the capability of firefox browser where .exe file is
located
WebDriver Remote_Obj = new RemoteWebDriver(new
URL("http://192.168.2.4:1007/wd/hub"), capability);
// Instead of using firefox/chrome driver we will use RemoteWebDriver
because it
// is connected to node machine with the ip address and port with URL.
Remote_Obj.get("https://www.google.co.in/?gws_rd=ssl");
System.out.println(Remote_Obj.getTitle());
Remote_Obj.quit();
8.) After the script is written on HUB machine we need to run that from
node
machine system.out.println will return on HUB machine but test case will
run on
node machine by opening browser and hitting URL.
*************************************************************************
******
Configuring Selenium with Eclipse and mini project using selenium
*************************************************************************
******
# Installed and configured on ubuntu 16.04
First install Java and Eclipse IDE on machine using sudo apt-get install.
In order to start create project and add selenium jars and libs to build
path.
ProjectName --> Properties --> Java Build Path --> Libraries --> Add
External
Once adding the all the jars and libs to the project we can see new
folder is
created in the project named as "referenced libraries".
For initial practice using chrome and firefox browsers for automating
test cases.
We need to download firefox and chrome drivers. For chrome we get easily
as per
system requirement one should download either 64 or 32 bit OS. For
firefox there
are not direct drivers one provided by the third party are from
geckodriver should
be downloaded.
Chrome
System.setProperty("webdriver.chrome.driver","/Path/to/chrome.exe");
ChromeDriver_Obj.getPageSource();
ChromeDriver_Obj.hashcode();
ChromeDriver_Obj.close();
ChromeDriver_Obj.quit();
So far we opened and closed url using automation technique. Now we need
to locate
objects in the page to automate for particular action.
Xpath will give address to particular node as example login page module.
This is
the best way to get object address where we want to automate fields.
There are also other object identification techniques like name, id,
class,
linked text, partiallinkedtext,tagname etc.
*************************************************************************
****
Selenium methods that are useful for webdriver testing
*************************************************************************
*****
Once creating obj with respective browser. Ex WebDriver Obj = new
ChromeDriver();
The selenium methods has to be applied in order to execute test cases
automatically.
1.) obj.get("www.xyz.com") - This will open the browser and hit the
specified URL
link specified
4.) String Title = Obj.getTitle() - This method will give the title
of the current page opened
5.) Obj.getPageSource() - This will give the code of the particular site
which
opened. We need pageSource to get the ID or unique element to get the
element.
close the browser i.e. which currently opened not the entire webdriver.In
case
of quit it will close entire webdriver i.e. it destroys all the instances
of
webdriver. It closes all browser windows associated with that driver and
safely
ends the session.
9.) Creating new tab is not possible with the webdriver this can be done
((JavascriptExecutor) Obj).executeScript("window.open('','_blank');"); -
This
javascript will open new tab which is blank.
To Select Drop down we can use different select class methods like
Select_DD.selectByVisibleText("Bengaluru (BLR)");
Select_DD.selectByValue("BLR");
** We can handle dropdowns using select class. First we need to pass the
address
of drop down as argument to Select class. Using the object created using
select
class we can choose methods like selectByVisibleText,SelectByIndex and
SelectByValue.
This will work only when class name is select other wise we have to use
alternate
approach creating List<WebElement> and then select according to index.
15.) To get the selected option as text in selenium we can use either of
the approaches below
DD_Ele.getAllSelectedOptions().get(0).getText();
or
16.) Select class will work only if the class name is select otherwise we
have to
use alternate way to handle this kind of situation. Using list getting
all dropdowns
into it and clicking on the desired dropdown using get method in it.
EX:
List<WebElement> options =
Chrome_Obj.findElements(By.xpath("//li[@role='option']"));
System.out.println(options.size());
17.) In orfer to handle the pop up there is a class called Alert. When
pop ups
arise they are not related to web page. The are kind of java or window
pops.To
handle this kind of pop up staright away apprach is using Alert class as
below
Once finding the drop down element address we need to click on it later.
Using
Alert class we need to switch window and accept or dismiss pop up.
EX :
WebElement Ele = Chrome_Obj.findElement(By.xpath("//select[@name =
'model']"));
// finding webelement address
Select DD = new Select(Ele);
// using select class we need to create object
DD.selectByIndex(2);
// selecting desired element using any of select class methods
Chrome_Obj.findElement(By.xpath("//input[@type = 'submit']")).click();
// After submitting with the desired element pop will arise
Alert Al = Chrome_Obj.switchTo().alert();
// Switching to alert window by creating object
System.out.println("Pop up message :" + Al.getText());
// To get text of pop up we can use getText method in Alert class
Al.accept();
// To say ok for pop up we need to accept. In order to decline we can use
dismiss
method
18.) In some cases Alert class will not work because pops are embedded
into the
html in this case we need to handle then with windowhandle operations.
EX :
String parentWindowHandler = Chrome_Obj.getWindowHandle(); // Store your
parent window
Chrome_Obj.findElement(By.xpath("//a[@class='one-way-tab bw-trip-
tabs']")).click();
Set<String> handles = Chrome_Obj.getWindowHandles();// get all window
handles
System.out.println("Size of handles :" + handles.size());
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
Chrome_Obj.switchTo().window(subWindowHandler);
Thread.sleep(2000);
Chrome_Obj.findElement(By.xpath(".//*[@id='globalModal']/div/div/div[3]/b
utton")).click();
Chrome_Obj.switchTo().window(parentWindowHandler);
19.) To handle the radio buttons if it is specified not to use xpath then
we
can use List<WebElement> object to handle all the types that are same.
EX :
List<WebElement> RB =
Chrome_Obj.findElements(By.xpath("//input[@type='radio']"));
// RB object will store all the radio buttons which are having same name
System.out.println(RB.size());
// This will return size of object having elements in it
RB.get(1).click();
// This will click on the second radio button in the webpage because
index starts
with 0
System.out.println(RB.get(1).getAttribute("value"));
// Getting the attribute of the selected radio button
20.) In order to handle check boxes we can use the xpath or any element
locator
technique. To click on the check box click() method can be used. To
validate that
we will use isSelected method. IsSelected Method will return true if box
is clicked
else false.
Ex :
boolean selc;
selc = Chrome_Obj.findElement(By.xpath("//*[@id='profession-
1']")).isSelected();
// Validating checkbox with isSelected method
System.out.println("Selected :" + selc);
Chrome_Obj.findElement(By.xpath("//*[@id='profession-1']")).click();
//clicking on checkbox
selc = Chrome_Obj.findElement(By.xpath("//*[@id='profession-
1']")).isSelected();
// validating with isSelected Method
System.out.println("Selected :" + selc);
EX :
if(Chrome_Obj.findElement(By.xpath("//*[@id='return-
date']")).isDisplayed())
{
System.out.println("Return field is displayed before oneway");
}
else
{
System.out.println("Return field is not displayed after oneway");
}
22.) isEnabled or IsDisabled methods which are used to enable and disable
the
choices we have. They will return true if it enabled or disabled
otherwise it
will return false. These are checkpoints to know whether object is
clicked or
not.
EX :
WebElement weee =
Chrome_Obj.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div[3]/u
l/li[8]/div[1]/a"));
// making object for the hover tab
Actions mouse = new Actions(Chrome_Obj);
// Using mouse actions to move on to the hover options.
mouse.moveToElement(weee).build().perform();
//This display other choices in the hover page
WebElement xyz =
Chrome_Obj.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div[3]/ul
/li[8]/div[2]/div[2]/div/ul/li[2]/a"));
// Creating the object for the choice we are interested in the hover
option
mouse.moveToElement(xyz).click().build().perform();
// Clicking on the hover option which we are interested in
EX :
EX :
WebElement newEle =
Chrome_Obj.findElement(By.cssSelector("a[href='/personal/customer-
centre']"));
// Locating element using cssSelector because it is having ui and li tags
Move.moveToElement(newEle).click().build().perform();
// Using mouse actions to move at that particular location
EX :
EX :
Chrome_Obj.get("https://netbanking.hdfcbank.com/netbanking/");
There different frame method available like frame(int index) which uses
frame index,
frame(string name) which take name of frame as argument and
frame(webElement ele)
which takes WebElement as argument.
29.) To get the number of links on whole webpage. We can use anchor a to
get number
of links. By using By.tagName method in selenium will be used to find the
elements and size() method will return number of links in page. Make sure
of using
findElements instead of findElement method.
EX :
List<WebElement> Ele = Chrome_Obj.findElements(By.tagName("a"));
// Getting all tagNames having a into list of webelements
System.out.println("Number of Links are :" + Ele.size());
// Using that webElement we can get size with size() method
System.out.println("Links are :" +
Chrome_Obj.findElements(By.tagName("a")).size());
// Combining both steps into one we can write as above
EX :
WebElement footerlinks =
Chrome_Obj.findElement(By.xpath(".//*[@id='glbfooter']"));
// Getting scope using findElement method
System.out.println("Footer links number :"
+footerlinks.findElements(By.tagName("a")).size());
// Getting size of links using findElements, tagName and size() methods
tr--> row
td --> under tr, columns in that row.
th--> under tr, header of column
We can get each row by using tagName method with argument tr and column
by tagName
method with argument td into it. Like wise for header we need to pass
argument
th.
Ex :
Chrome_Obj.get("http://www.espncricinfo.com/sri-lanka-v-bangladesh-2016-
17/engine/match/1083448.html");
WebElement table =
Chrome_Obj.findElement(By.xpath("//table[@class='batting-table
innings'][1]"));
// In order to access particular table using any of the locator technique
Thread.sleep(1000);
int i = 0;int sum =0;
for(WebElement col : table_rows)
// getting colums in each row using for each loop
{
for(WebElement header:table_header)
{
System.out.println(header.getText());
}
32.) When we hit the URL and clicking on some link on it. Sometimes there
may be
slow internet connection due to this. When we click on URL, even if the
webpage
is not completely loaded it will search for link on the page we
specified. Webdriver
will proceed further step this cause synchronization issue. To make
webdriver
wait till page is completely loading before clicking on link we will use
wait.
We have two types of waits they are implicit wait and explicit wait.
We can use Thread.sleep(5000) 5 seconds to wait the driver in the next
step we need to
wait for some time. Writing Thread.sleep() at every step causes
performance issue.
So we declare some amount of time globally. If the link load before
specified time
then moving further operations.
a.)In implicit wait if the link is opened before specified time then
script will
continue further. In explicit wait it will wait till specified time
irrespective
of loading the web page.
EX :
b.)In explicit wait is local wait method which will wait for specified
amount of time
irrespective of the page loading. This will cause performance issue.
EX :
WebDriver Chrome_Obj = new ChromeDriver();
Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");
//Thread.sleep(10000);
// This will wait 10 secinds irrespective of page loading. It will
proceed further operations
//after 10 seconds in the script. It is local wait system. This will
cause performance issue.
c.) An explicit wait is code you define to wait for a certain condition
to occur
before proceeding further in the code. There are some convenient methods
provided
that help you to write code that will wait only as long as
required.WebDriverWait
in combination with ExpectedCondition is one way this can be
accomplished.
EX :
WebDriver Chrome_Obj = new ChromeDriver();
Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");
WebDriverWait waittime = new WebDriverWait(Chrome_Obj,10);
//This is same as above method explicit wait condition but it will wait
till the condition is
// fullfill
WebElement wait_condition;
wait_condition =
waittime.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//
*[@id='gbw']/div/div/div[1]/div[2]/a")));
// webdriver wait condition till finds the element By.xpath in page
wait_condition.click();
Chrome_Obj.quit();
d.) Fluent Wait Command: Each FluentWait instance defines the maximum
amount of
time to wait for a condition, as well as the frequency with which to
check the
condition. Furthermore, the user may configure the wait to ignore
specific types
of exceptions whilst waiting, such as ‘NoSuchElementExceptions’ when
searching
for an element on the page.
Ex :
WebDriver Chrome_Obj = new ChromeDriver();
Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");
FluentWait<WebDriver> fwait = new
FluentWait<WebDriver>(Chrome_Obj).withTimeout(30, TimeUnit.SECONDS);
fwait.pollingEvery(5, TimeUnit.SECONDS);
fwait.ignoring(NoSuchElementException.class);
// creating fluent wait object with time, frequency ane exception
// we are declaring a fluent wait with the timeout of 30 seconds and the
//frequency is set to 5 seconds by ignoring "NoSuchElementException"
EX :
Chrome_Obj.manage().deleteAllCookies();
// This will delete all the cookies of the browser we are interested in
example
// chrome here
Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");
Chrome_Obj.manage().window().maximize();
// This will maximize the window of the webpage.
34.) To delete cookies we can use method in manage. In order to get the
cookies
also we can use collections Set.
Ex :
Set<org.openqa.selenium.Cookie> Cookies_brw =
Chrome_Obj.manage().getCookies();
// Getting the cookies into the Set with object Cookies_brw
System.out.println(Cookies_brw.size());
// To get size of cookies above command can be used
Chrome_Obj.manage().deleteAllCookies();
// To delete all cookies in the webpage
EX :
FirefoxProfile prof = new FirefoxProfile();
// Creating firefox profile
prof.setAcceptUntrustedCertificates(false);
//setting the HTTP handle to false which will accept all untrusted
certifications
WebDriver Firefox_Obj = new FirefoxDriver(prof);
// Sending profile as argument to FirefoxDriver
Firefox_Obj.get("https://www.google.co.in/?gws_rd=ssl");
Firefox_Obj.quit();
EX:
WindowsUtils.tryToKillByName("notepad.exe");
EX :
Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");
Chrome_Obj.quit();
39.)
*************************************************************************
*****
Mouse and Keyboard Actions using Selenium :
*************************************************************************
*****
Actions class used to move mouse to particular location. In other words
actions class
is used to hover on to the element. Mouse hover actions can be performed,
context menu
options can be done etc.
1.) First we need to create the webdriver object and later create
webElement
where we want mouse to move that element.
Ex :
WebDriver Obj = new ChromeDriver();
Actions Mouse_Move = new Actions(Obj);
// creating mouse move with Actions
Ele_loc.sendKeys("");
// This will set focus on the element we are looking at
Mouse_Move.moveToElement(ele_loc).build().perform();
// Making mouse to element we are interested
Mouse_Move.click();
//Clicking on element we are interested in.
Here build and perform methods are routine in actions class because they
will
perform actions more succiently where we want to move mouse or do some
actions.
EX :
WebElement Ele_search =
Chrome_Obj.findElement(By.xpath("//*[@id='twotabsearchtextbox']"));
// This will find the element location where we want to type text
moment.keyDown(Keys.SHIFT).moveToElement(Ele_search).sendKeys("cellphone"
).build().perform();
// keyDown method is use with Keys.SHIFT to make text as caps
In some cases it will not work directly with the above approach alternate
way is
below
EX :
WebElement Ele_search =
Chrome_Obj.findElement(By.xpath("//*[@id='twotabsearchtextbox']"));
// get the element where we are interested
moment.sendKeys(Keys.SHIFT).moveToElement(Ele_search).click();
// Sending keys using click to making sure we are focused on the element
moment.sendKeys("apple").build().perform();
// Sending text using sendKeys
3.) If we do right click on the mouse we will get options available this
menu
is called Context menu. To get the context menu we have to use
contextClick()
method.
EX :
WebElement Ele_search =
Chrome_Obj.findElement(By.xpath("//*[@id='twotabsearchtextbox']"));
// Element we are interested in
moment.contextClick(Ele_search).build().perform();
// getting context menu using contextClick()
4.) dragAndDrop(src, dst) This method will move the object from one
location
to the other. Src is source webElement and dst is destination webElement
where
we want to drag and drop element of src.
*************************************************************************
*****
Locating Objects
*************************************************************************
*****
//tagname[@attribute = 'value']
using syntax
//img[@src='http://theosteria.in/wp-content/uploads/2016/06/first1.png']
Ex :
Obj.findElement(By.xpath("path")).click();
If there is any text on the clickable element we can use text() as below
//a[contains(text(),'MENU')]
//a[(text()='MENU')]
We can use AND and OR also to get accurate locator of the element.
2.) Xpath :
Ex :
Obj.findElement(By.xpath("path")).click();
3.) ID :
The Id is another identification technique where we can able to click
element on
the page using ID.
EX :
<input id="email" class="inputtext" name="email" value="" tabindex="1"
type="email">
Here ID is email.
Obj.findElement(By.id("Id")).click();
4.) Name
Name is another identification technique. Where we can able to locate
element on
webpage using name.
EX :
<input id="email" class="inputtext" name="email" value="" tabindex="1"
type="email">
Obj.findElement(By.name("name")).click()
5.) LinkText
This is another object identification technique. It will be available at
the end
of anchor symbol as below.
EX :
<a style="color: #800000; text-decoration: underline;"
href="http://theosteria.in/everyday-continental-breakfast/">MENU</a>
Obj.findElement(By.linkText("MENU")).click();
6.) Partial LinkedText
Here partiallinktext name is at the end before </a> which is Men. Even if
we guve
men it will automatically identify and take it as menu.
Obj.findElement(By.partialLinkText("MEN")).click();
EX :
<input id="email" class="inputtext" name="email" value="" tabindex="1"
type="email">
Ex :
<input id="email" class="inputtext" name="email" value="" tabindex="1"
type="email">
input[id='email'] is CssSelector
Obj.findElement(By.CssSelector("input[id='email']")).click();
*************************************************************************
*****
TIPS & TRICKS :
*************************************************************************
*****
1. While locating elements it is good idea to cross check once if there
are any
matches to it.
3. If there are same for xpath or Id mutiple things were highlighted use
some
AND/OR operation or try to find out unique element some other things has
to be
obtained by using any of the axes mode. This is primarily important to
locate
unique element. Reference from guru99 is used to get xpath.
http://www.guru99.com/xpath-selenium.html
*************************************************************************
*****
Cloud Testing Using Sauce Labs
*************************************************************************
*****
Sauce labs is game changing commercial tool which helps to execute the
test script
on various browsers and OS. It is also called as cloud based testing. It
is designed
mainly to execute the test cases using different browsers, cross paltform
and
parallel testing etc.
Among all sauce labs is commercial tool which support wide varieties of
cross
browsers, cross platform and also parrallel testing. Test execution on
sauce is
simple, once we write test script runs as usual with a few minor edits.
Then
WebDriver sends execution commands to our hosted browsers and devices on
the
cloud i.e. sauce labs.
Ex :