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

Selenium

The document discusses whole architecture of testing including manual testing, automation testing using Selenium and various frameworks like keyword driven and data driven. It explains the need for automation testing to overcome limitations of manual testing. Key reasons for automation testing include reducing human effort and errors in repetitive testing. The document also describes various test management and defect tracking tools. It provides details about Selenium and reasons for its preference over other automation tools.

Uploaded by

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

Selenium

The document discusses whole architecture of testing including manual testing, automation testing using Selenium and various frameworks like keyword driven and data driven. It explains the need for automation testing to overcome limitations of manual testing. Key reasons for automation testing include reducing human effort and errors in repetitive testing. The document also describes various test management and defect tracking tools. It provides details about Selenium and reasons for its preference over other automation tools.

Uploaded by

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

-------------------------------------------------------------------------

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

BugZilla, Mantis and Customized Excel sheet

Test Management Tools :


(Defect tool + Test Management)

JIRA, ALM (Application life cycle management) and MTM(Microsoft test


management)

*************************************************************************
******
Why we need automation testing ?
*************************************************************************
******

Testing plays crucial role in the development of product. Without testing


product
it is challenging for any company to continously maintain and improve the
quality
and efficiency.In case if testing is neglected because of time or cost
contraints
leads to lack of product quality, followed by customer dissatisfaction
and increase
overall quality costs. The main reasons for these added costs are
primarily poor
test strategy, underestimated effort of test case generation, delay in
testing
and subsequent test maintenance.

Manual testing is performed by human sitting infront of a computer


carefully executing
the test steps. In practical world it highly tedious and pain taking task
to
re-executing tests several times. Especially when doing regression
testing,
if any issue arises in some cases we need to do unit, regional and full
regression
testing.These makes humans to get bored, error prone and mundane while
executing
test cases manually. As a result humans will lose interest in executing
tests manually.
It is ok for testing single test case for one or couple of times. If it
goes to
10's, 100's or 1000's then it turns out to be monotony job. So, humans
will not
able to do these tasks with same interest and enthusiasm. So there is
waste
of time and efforts in retesting these.

In order to overcome these factors, one uses automation testing.


Automation means
using an automation tool to execute test case suite. Test automation
software can
also enter test data into the system under test, comparing expected and
actual
results with detailed test reports. Test automation demands considerable
investment
of money and resources. Successive development cycles will require
execution of
same test suite (test script) repeatedly. With test automation tool it is
possible
to record this test suite and replay as it is required. Once the test
suite is
automated, no human intervention is required. This improves ROI (Return
of Investment)
of test automation.

It is clear about dark side of manual testing. To overcome these cons we


are using
automation testing.Main goal of automation is to reduce number of test
cases to
be run manully and not to eliminate manual testing at all. There are few
reasons
why we use automation testing
- Manual testing of all work flows, all fields, all negative scenarios
is time
and cost consuming.
- It is difficult to test manually multi lingual sites
- Automation doesn't require human intervention
- Automation increases speed of test execution
- It helps to increase test coverage
- Manual testing is mundane, error prone and boring etc.
- ROI is quiet fast and high in the long run
- Less human resources are required for automation (Test automation
engineer and
test scripts)
- Reusability of automation scripts (Using same script on hundreds of
devices
and same tests every time)
- Finding bugs in early stages of development can reduce expenses and
working hours.
- Simulataneity running test scripts simultaneaous on different devices.
- Continuity building up new test cases based on old test cases.
It is not possible to automate all the test cases. Test cases to be
automated can
be selected using the following criterion to increase the automation ROI
- High risk - business critical test cases
- Test cases that are executed repeatedly
- Test cases that are very difficult to perform manually
- Test cases which are time consuming

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.

In both manual and automated testing environments test cases need to be


modified
for extended periods of time as the software project progresses. It is
important
to be aware that complete coverage of all tests using test automation is
unrealistic.
When deciding what tests to automate first, their value vs. the effort to
create
them needs to be considered. Test cases with high value and low effort
should be
automated first. Subsequently test cases with frequent use, changes, and
past
errors; as well as test cases with low to moderate effort in setting up
the test
environment and developing the automation project are best suited for
automation.

Automated testing process is followed by the below steps


- Test tool selection
- Scope of automation
- Planning, Design and Development
- Test execution
- Maintenance

Test tool selection largely depends on the technology the application


under test
(AUT) is built on. As an example QTP doesn't support informatica. So QTP
cannot
be used for testing informatica applications. It is good idea to conduct
proof
of concept (POC) of tool on AUT.

A proof of concept (POC) is a demonstration, the purpose of which is to


verify
that certain concepts or theories have the potential for real-world
application.
POC is therefore a prototype that is designed to determine feasibility,
but does
not represent deliverables. Proof of concept is also known as proof of
principle.
There are several tools available in market like selenium, QTP, Rotation
functional
tester, watir, silk test ect. Tool has to be selected against automation
requirements
not as per its demand or popularity. In order to do functional and
regression testing
we need any tool like selenium, silk test etc. Here our automation
requirements
are function and regression so we can choose any of those.

Scope of automation is the area of our AUT which will be automated.


Following
points help to determine the scope
- Features that are important for the business
- Scenarios which have large amount of data
- Common functionalities across applications
- Technical feasibility
- Extent to which business components are reused
- Complexity of test cases
- Ability to use the same test cases for cross browser testing

Planning, Design and development phase allows us to create automation


strategy
and plan, which contains following details
- Automation tools selected
- Framework design and its features
- In scope and out of scope items of automation
- Automation test bed preparation
- Schedule and timeline of scripting and execution
- Deliverables of automation testing

Test execution allows to execute automation scripts. The scripts need


input test
data before there are set to run. Once executed they provide detailed
test reports.
Execution can be performed using the automation tool directly or through
the test
management tool which will invoke the automation tool.

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.

Different types of software testing that can be automated are smoke


testing, unit
testing, integration, function, keyword, regression, data driven and
blackbox testing.

*************************************************************************
*****
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 ?
*************************************************************************
******

In order to do automation there are plenty of tools available. Some of


them
are open source and other are encumbered with license. Among them
Selenium,
QTP, Rotational functional tester, watir and silk test etc. In these some
supports
exclusively some browsers, some have extra options like play back, some
supports
few programming languages etc. Automation tool has to to be selected
based on
features we need to automate but not based on its popularity. But among
all
selenium is widely prefered in the market not on its popularity but on
its
interesting features available. Lets see why selenium is more useful than
others.

- Selenium is a suite of software tools to automate the web browsers.


- Selenium is an automation tool used for functional and regression
testing
- Selenium is open sourced tool (where company saves lots of its budget
using
this rather than purchasing licensed version)
- It is used exclusively for webbased applications
- It is avaliable to work on multiple operating systems like windows, OS
X, Linux,
Solaris etc
- It supports wide varity of languages like Java,C#, Ruby, Python, PHP
and Pearl.
Almost in 6 programming languages one can write automation script.
- Selenium support different browsers in particular number IE, Firefox,
Chrome
and Safari.
- One highly beneficial feature of selenium is that the language used for
building the program is independent of the language that the web
application or
website is used (built on native language). This implies that the test
script
can be developed in any of the languages that selenium supports.
-Selenium has a very dynamic developer community that is backed by
google.
-For selenium is concerned, we have a number of robust methods for
location of
elements such as CSS,Xpath, DOM etc.
-With selenium, it is convenient to implement frameworks that resolve
around
object oriented programming like keyword driven, data driven, modular and
hybrid
automation framework.
-Selenium provides support for integration of opensource framework like
TestNG,
JUniy,NUnit and so on.
-With the use of selenium, it is possible to execute simultaneous tests
leveraging various browsers on various machines. This is turn cuts down
the time
for test execution when large projects is in progress.

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

As we see selenium has more advantages when compared to other. So it is


used by
most of the companies.

*************************************************************************
******
History of Selenium ?
*************************************************************************
******

Selenium was started in 2004 by Jason Huggins. In 2006 selenium webdriver


was
launched at google. In 2008, whole selenium team decided to merge
selenium
webdriver to selenium RC in order to form more powerful tool called
selenium 2.0.
Selenium 1.0 three tools were provided Selenium IDE + Selenium RC +
Selenium Grid.
Selenium 2.0 four tools were provided Selenium IDE + Selenium RC +
Selenium Webdriver
and Selenium Grid. In order to overcome some issues in Selenium RC,
selenium
Webdriver is launched. Selenium RC is used for maintaining the projects.
For
new application selenium webdriver is used.

*************************************************************************
******
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

- Selenium IDE (Integrated Development Environment) :


----------------------------------------------------
Selenium Integrated Development Environment (IDE) is the simplest
framework in
the Selenium suite and is the easiest one to learn. It is a Firefox
plugin that you can install as easily as you can with other plugins.
However, because of its simplicity, Selenium IDE should only be used as a
prototyping tool. If you want to create more advanced test cases, you
will
need to use either Selenium RC or WebDriver. Since it is plugin for
firefox it
will not support other browsers. Selenium IDE commands called selens
commands
which are used to enhance test cases.

Selenium IDE features :

--> Create test cases, test suites


(Record and Type test steps)
--> Edit test cases
--> Execute test cases, test suites
--> Debug test cases
--> Enhance the test cases
--> Export test cases to other supporting formats(default format is html,
we can
export it to java, ruby etc). But this feature is not working upto the
mark.

Drawbacks of Selenium IDE :

--> It supports only firefox browser only.


--> It doesn't support programming logic/features to enhance test cases.
--> It doesn't support data driven testing
(Data driven testing the same functionality with different sets of test
data)
--> It is not suitable for complex test case design because of no
programming support.
--> No centralized maintainence of elements/objects.
(Based on front end objects (like check box, radio buttons etc) only
funtional test
tools can do functional testing)

- Selenium RC (Remote control server):


-------------------------------------
Even though it is similar to webdriver which can do all operation but it
is outdated.
The selenium RC architecture gives brief overview of it and its drwabacks
which
make it outdated.

------------- --------- -----------


| | |Proxy | |Applicati|
| Editor |-------> |server | ------> |on to |
| | | | |test |
------------- --------- -----------

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.

Basically it is programming we need to write script for each test case.


Selenium
web driver supports various programming languages(java,python,C#, perl,
PHP and
Ruby). It supports various browsers like chrome, firefox,IE, Safri, Opera
etc.
It can operate in various Operating systems like MS windows, Linux,
Macintosh etc.

Drawbacks of Selenium WebDriver:


--> No built result report facility.
--> Selenium WebDriver has no IDE, takes more time to create test cases.
--> It doesn't have an integrated spread sheet for data driven testing.

- 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

Here in the node 1-3 are different combination of OS and browsers. It is


cross
browser testing. Where we can execute test case on application with
different
browsers and OS. We will have test case in local machine only using ip
address
of other machines to trigger the execution. In the architecture HUB is
place
where we will do all the operations it is also local machine where we
have selenium
script and distributed to other remote machines. Nodes are remote machine
where
we can run the test case on it. HUB will gives task to the node.

1.)First we need to download selenium standalone server from


seleniumhq.org.
2.)After downloading jar file then we need to say selenium that local
machine
is hub i.e. we need to start hub. So we need to excute the below command
by setting
path where jar file is located.
java -jar selenium-server-standalone-3.3.1.jar -role hub
3.)To check whether server is started in local machine which we are using
as hub
can be done by using url http://localhost:4444/grid/console
By clicking on url it will open grid console on webpage.
4.) Getting IP address of HUb machine. Has to type on broswer of node
machine
http//IP.Address.IPv4:4444/grid/console. This will make us to access that
HUB
from any node.
5.)To register node the hub. First we need to download selenium.sever
standalone
in node machine. In the cmd prompt or terminal we need to go for the
location
where selenium standalone server was downloaded using cd. Then enter
command below
java -jar selenium-server-standalone-3.3.1.jar -role node -hub
http://IP.Address
.IP4:4444/grid/register -port 5567
Here 4444 is port will send tasks. The tasks are executed on the port of
remote
machine its port is 5567. Which starts execution.
6.) The above command will register remote machine as node. To check node
is
registered and ready to interact and listen from HUB. We need to switch
to HUB
machine and click url http://localhost:4444/grid/console. It will gives
node
machine IP address. That is default remote proxy. When we execute test
script
HUB machine talks with node and runs in that IP address.
7.) Writing the script in the HUB machine and running it from the HUB
machine will
invoke on the remote machine. The code is explained in detail below.

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.

For more details information refere to link below


https://github.com/SeleniumHQ/selenium/wiki/Grid2

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

Google selenium webdriver and downloaded 64bit. Extracted them into


folder.

In order to start create project and add selenium jars and libs to build
path.

ProjectName --> Properties --> Java Build Path --> Libraries --> Add
External

Jars and Libs --> Apply/OK

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.

To open the url we wish to in the example http://theosteria.in/ is used.


Before
opening url we need to set propeerty of driver or browset we need to
test.

Chrome
System.setProperty("webdriver.chrome.driver","/Path/to/chrome.exe");

Creating chrome driver object using oops

webdriver ChromeDriver_Obj = new ChromeDriver();// creating object for


chrome driver
ChromeDriver_Obj.get("http://theosteria.in/"); //passing url to open on
browser

** Make sure url should contain http or https. If we give directly


www.xyz.com
will throws error.
String CheckUrl = ChromeDriver_Obj.getCurrentUrl(); //gives current url
open on browser

Now we need to check whether opened url is same as we given or not

boolean Result = url.equals(CheckUrl); //checking both urls are same or


not

we can use System.out.println to see the result.

To get title of the url

String Title = ChromeDriver_Obj.getTitle();

To get page source

ChromeDriver_Obj.getPageSource();

To get hashcode which is unique code when object is created

ChromeDriver_Obj.hashcode();

To close the browser we have to use the following

ChromeDriver_Obj.close();

In order to quit the webdriver

ChromeDriver_Obj.quit();

There is difference between close and quit in selenium. Close will be


used to
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.

So far we opened and closed url using automation technique. Now we need
to locate
objects in the page to automate for particular action.

In order to use that for firefox we need firebug and firepath as


extensions to
the browser where we will get information of objects easily in various
ways
like Xpath,HTML,CSS,DOM,.Net,DOM etc. These are the object identification
techniques.

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

2.) String s = obj.getCurrentURL() - This method will return the current


URL to
s variable which is string.

3.) obj.findElement(By.xpath("Specify xpath")).click() - This method will


click
on the particular clickable element on the webpage. Xpath can be obtained
by using
readymade tools like firebug or any other. Other standard way of getting
xpath
is using the customized xpath which we will create our own xpath. See
Locating
objects below.

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.

6.) Obj.hashCode() - To get hashcode which is unique code when object is


created

7.) Obj.close() - To close the browser

8.) Obj.quit() - To quit the webdriver

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.

ArrayList<String> tabsList = new


ArrayList<String>(Obj.getWindowHandles()) - This
method will create Arraylist with copy of getWindowHandles().
Obj.switchTo().window(tabsList.get(1)); - This method will be used to
shift the
focus on to the new tab. So that we can enter new url using get() method

10.) Obj.navigate().back() - This method will go back to the previous


page.

11.) obj.findElement(By.Xpath("Path")).SendKeys("[email protected]") - This


method
is used to send data to the field which we located using object location
techniques
below.

12.) Obj.manage().deleteAllCookies() : This method will be used to delete


all
cookies. In some cases we need to enter some input differently as we do
in
login page. In this case if we deleteAllCookies() it will ask for new
text data
into the field. If cookies were not deleted previously stored information
will
be obtained from the memory.

13.) Getting focus on the element using java script


JavascriptExecutor executor = (JavascriptExecutor) Chrome_Obj;
executor.executeScript("arguments[0].click();", Menu);

The simplest approach is using sendKeys("") empty to the focused element.


In some
cases it may not work so javascriptExecutor will work for us.

14.) Select is a class in selenium webdriver to handle drop down buttons.


Creating object for Select looks like below
Select Select_DD = new Select();

To Select Drop down we can use different select class methods like

Select_DD.selectByVisibleText("Bengaluru (BLR)");

Select_DD.selectByIndex(26); --> This throws error select

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.

Select_DD.isMultiple() returns true if dropdown is having mutiple


selection otherwise
false.

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

WebElement text_is = DD_Ele.getFirstSelectedOption();


String DD_text = text_is.getText();

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

// index starts from 0


System.out.println(options.get(20).getText());
options.get(4).click()

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.

First we need to create collection set to getWindowHandles.Using iterator


we can
switch to desired window. Doing pop up operation using xpath in this case
will
work. Once pop operation is done then we can switch to parent window or
default
source and doing other operations can be done. When elements are in list
it will
start with index 0.

EX :
String parentWindowHandler = Chrome_Obj.getWindowHandle(); // Store your
parent window

String subWindowHandler = null;

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

21.) isDisplayed method is used to check whether that field is displayed


or not
it depends on the previous choice we made as an example in one way return
date
will not be displayed. isDisplayed Method returns true if field is
displayed otherwise
it will return false.

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.

23.) In order to handle the Ajax Mouse interactions we need to use


Actions class.
This is an alternate way if the webpage is designed with mouse
interaction to
display the choices/options in the particular location then we will use
Actions
class. See below of Mouse and Keyboard actions with examples.

24.)In order to handle hoverpages. First we need to locate the element


using any
of the locator techniques later using Actions class moving mouse to
particular
location. Then hover options will appear again select the hover option we
want
then choose with any of the locator techniques. Moving mouse Actions
class to
that location and use click method to open that hover option.

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

25.) Some time inorder to automate the notifications or pop up we cannot


able
to use Alert class and also window handle approach. In this situation we
can
use frame provided on the notification tab. Using
switchTo().Frame("FrameName").
Then we can perform operations on that page using any of the locator
techniques.
After completing this option we need to return to parentwindow using
switchTo().defaultContent() method we can do operations on the tab.

EX :

WebDriver Chrome_Obj = new ChromeDriver();


// Creating chrome dirver object
Chrome_Obj.get("http://www.hdfcbank.com/");
// Hiting on the link we want
Chrome_Obj.switchTo().frame("http-push");
// This will open notification or pop up. So we are switching to frame to
handle
// pop ups
Chrome_Obj.findElement(By.xpath("//*[@id='closeImage']")).click();
//Choosing appropriate option we want on the pop up window
Chrome_Obj.switchTo().defaultContent();
// Again switching to default window to do other operations.

26.) In some scenarios we will have ui and li tags in this situation it


is good
to go with cssSelector locator technique. Using xpath axes method will
also be
useful.

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

27.) Sometimes when we click on an element it will redirect to new tab


and opens
information of particular element. In this case we need to handle
elements efficiently
First we need to store the current windowhandle to some string. And then
using
switchTo() window where we want to perform some operations after
finishing operation
in the child window we need to close that window and again switching back
to
parent window and doing necessary operations we want.

EX :

String ParentWindow = Chrome_Obj.getWindowHandle();


// Storing window handle in parentWindow
for(String NextWindow : Chrome_Obj.getWindowHandles())
{
Chrome_Obj.switchTo().window(NextWindow);
}
// Using for loop for next window switching if available using
getWindowHandles.
WebElement newEle =
Chrome_Obj.findElement(By.cssSelector("a[href='/personal/customer-
centre']"));
// Using cssSelector to get WebElement.
Move.moveToElement(newEle).click().build().perform();
// Moving mouse to required WebElement using Actions class
Chrome_Obj.close();
// Closing child window where operations are finished
Chrome_Obj.switchTo().window(ParentWindow);
// Switching again to parent window

28.) Handling Frames is important and advanced part of selenium. Frames


are kind
of html document which are embedded on other html document. If there is
contiguous
change in web page which is dynamic then developer perfer to embedded
this as html
into other html. As an example flash/breaking news on newpaper
websites.Using selenium
it is difficult to find the element on that embedded html page. When we
locate
element exactly on the page then it will throw error message "unable to
find the
element". If the application is built on frames then developer will uses
either
of these two tags Iframe and frameset.This is kind of check point that
application
is built on frames. If it is build using iframe then developer provides
id for that
but for framset we need to check and use that because id will not be
available.

EX :

WebDriver Chrome_Obj = new ChromeDriver();

Chrome_Obj.get("https://netbanking.hdfcbank.com/netbanking/");

System.out.println("Page Source is : \n" + Chrome_Obj.getPageSource());


Chrome_Obj.switchTo().frame(0);
// Switching to frame
WebElement location =
Chrome_Obj.findElement(By.cssSelector("input[class='input_password']"));
// creating object using cssSelecto
Actions Mouse = new Actions(Chrome_Obj);
Mouse.moveToElement(location).click().build().perform();
// Moving mouse to specific element using Actions class
Mouse.moveToElement(location).sendKeys("21086240").build().perform();
// Sending keys to the location where we want.

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

30.) We can restric our search to particular area using findElement. In


other
words we can limit the scope of the url where we are interested in. Using
tagName
and size() method with findElements to get links in the scope we are
interested
in.

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

31.) WebTable handling using selenium webdriver. It is nothing but a


table having
rows and columns. In order to find whether web application is having
webtable
or not can be identified whether it contains tr and td tags in the
webpage.tr tag
represents for writing rows in the table and td tag is for writing
particular
data for row in table. By seeing page source or html of the page we can
conclude
that web application is having web table. For each tr tag we will have
multiple
columns. At the same time after every tr tag it has columns of that row.
New row
will have tr and td tags.

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 :

WebDriver Chrome_Obj = new ChromeDriver();

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

List<WebElement> table_rows = table.findElements(By.tagName("tr"));


// using tagName to find number of rows in table
System.out.println("Number of rows are :"+ table_rows.size());

Thread.sleep(1000);
int i = 0;int sum =0;
for(WebElement col : table_rows)
// getting colums in each row using for each loop
{

List<WebElement> table_cols = col.findElements(By.tagName("td"));


// scope of search is limited to cols and table we are interested in
System.out.println("Number of cols in row " + i + " is :" +
table_cols.size());
// Number of columns in each row
sum = sum + table_cols.size();
List<WebElement> table_header = col.findElements(By.tagName("th"));
System.out.println("Number of cols in row " + i + " is :" +
table_header.size());

for(WebElement header:table_header)
{
System.out.println(header.getText());
}

// To get text of each column using getText() method


for(WebElement text:table_cols)
{
System.out.println(text.getText());
}
i++;
}
//System.out.println("Sum of cols are :" + sum);
Thread.sleep(1000);
Chrome_Obj.quit();

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 :

WebDriver Chrome_Obj = new ChromeDriver();


Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");
Chrome_Obj.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// This will wait maximum 10 seconds if page loads before 10 seconds it
will proceed with
// further operations in the script. It is globally wait system

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"

WebElement Click_ele = fwait.until(new Function<WebDriver, WebElement>()


{
public WebElement apply(WebDriver Chrome_Obj)
{
return
Chrome_Obj.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[2]/a")
);
}
});
//created a new function to identify the Web Element on the page.
//(Ex: Here Web Element is nothing but the selenium link on the webpage)
//Frequency is set to 5 seconds and the maximum time is set to 30
seconds.
//Thus this means that it will check for the element on the web page at
every
// 5 seconds for the maximum time of 30 seconds. If the element is
located within
// this time frame it will perform the operations else it will throw an
//"ElementNotVisibleException"
Click_ele.click();
// Clicking on element we are interested in
Chrome_Obj.quit();

33.) To do some operation on window we can use methods in manage(). It is


used
to set time for loading page and maximizing window etc.

EX :

WebDriver Chrome_Obj = new ChromeDriver();

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

35.) In order to Handle SSL/HTTPs certification we need to create profile


first
then we have to send that profile as argument to the
ChromeDriver(profile). When
ever HTTPs/SSL error encounter it will automatically handle that
irrespective
to the through the script.

SSL-Secure Socket Layer; HTTP- Hypertext transfer protocol

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

In chrome and IE we dont need to write profile specifically because thrid


party
vendor provide which will be available in .exe file.

36.)There will be some scenarios where browser will not be invoked. In


chrome
and IE we need to use System.SetProperty(Webdriver.name,'path to exe')
In fire fox we need to do in other way around. It could happen if we have
couple
of .exe file at different locations then webdriver will get confuse. So
to handle
this we need to say where exactly .exe file is located.
Ex :
FirefoxBinary ffBinary = new FirefoxBinary("path to .exe file");
FirefoxProfile ffprofile = new FirefoxpProfile();
Firefox_Obj = new FirefoxDriver(ffBinary,ffprofile);

This approach is called troubleshooting the firefox driver.

37.) Killig the process in selenium can be done using tryToKillByName


method.This
will be used when we use data driven we will open excel sheet to get the
data.
In this type of situation we need to kill the task process for the next
run.

EX:
WindowsUtils.tryToKillByName("notepad.exe");

38.)Taking screenshot using selenium through getScreenshotAs() method. It


is not
a direct method we can achieve it by means of TakeScreenshot class. First
we need
to cast the object with TakeScreenshot class the using getScreenshotAS
method is
used to get screen shot. To copy it into particular folder we need to use
copyFile
method in FileUtils.

EX :

WebDriver Chrome_Obj = new ChromeDriver();

Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");

File scrFile = ((TakesScreenshot)


Chrome_Obj).getScreenshotAs(OutputType.FILE);
// Casting Chrome_Obj to TakeScreenshot and using getScreenshotAs method
FileUtils.copyFile(scrFile, new File("/home/go-geeky-chakon/Desktop/Books
to complete/Software Testing/Selenium Webdriver Tutorial
Basics+Advanced+Interview Guide/Selenium Webdriver Tutorial
Basics+Advanced+Interview Guide/09 Famous INTERVIEW
QESTIONS/screenshots/screen.png"));
// Using copyFile method to copy the screenshot to particular location

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

WebElement ele_loc = Obj.findElement(By.xpath("Xpath/any locator


technique"));
// Getting element from the page

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.

Or we can combine last two steps like


//Mouse_Move.moveToElement(ele_loc).click().build().perform();

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.

2.) In order to do keyboard operations we will use keys in the Actions


class.
To type the text in caps we can use keys.down method where we will send
keys.SHIFT
as argument to them.

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.

5.) Other methods like clickAndHold, doubleClick() etc which we will


perform
using keyboard and mouse.

*************************************************************************
*****
Locating Objects
*************************************************************************
*****

1.) Cutomized Xpath basic syntax

//tagname[@attribute = 'value']

example for this


<img src="http://theosteria.in/wp-content/uploads/2016/06/first1.png">

tagname come after "<" so tagname=img


attribute = src
value = "http://theosteria.in/wp-content/uploads/2016/06/first1.png"

using syntax
//img[@src='http://theosteria.in/wp-content/uploads/2016/06/first1.png']

In case if we have only href is available


//a[@href='http://theosteria.in/weekend-buffet/'] or
//a[contains(@href,'http://theosteria.in/weekend-buffet/')]

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 :

This is major object location technique used. It is unique address to


identify
the object on the webpage. This is like particular address to the node.
To get the Xpath we can use Firebug tool in firefox and f12 in chrome and
other.
With the help of these tools we can highlight the field we want to click
and
export xpath from it. Use that xpath in the code.

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">

Here name = "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>

Here linktext name is at the end before </a> which is Menu.

Obj.findElement(By.linkText("MENU")).click();
6.) Partial LinkedText

This is another locator technique which is used if the linktext is not


exactly
same it will try to find automatically.

EX : <a style="color: #800000; text-decoration: underline;"


href="http://theosteria.$

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

7.) Class Name

It is used to identify the clickable element on the webpage.

EX :
<input id="email" class="inputtext" name="email" value="" tabindex="1"
type="email">

Here class = "inputext";

8.) CssSelector is another way to locate the webelement. Infact this is


10x times
much faster than xpath. The class under the class can be identified using
Css only.
It is similar like writing customized xpath without special character in
it.

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.

2. Sometimes there will be situation like clickable element at the end of


the
page it has to get into focus. It might now work directly with xpath and
click.
So alternate way is create web element and at the same time. To that
webelement
sendKeys("") which are empty. So that focus will be sent to it.

Excuting javascript is alternate choice.


JavascriptExecutor executor = (JavascriptExecutor) Chrome_Obj;
executor.executeScript("arguments[0].click();", Menu);

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

4.To handle web based alters or notification we need to use window


handles to do so.
But in some situation it is not possible so if it is designed with frames
then we
can use that information to handle frames. It is used to switch from one
window
to other using frames.

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

The interesting question to answer is why we need to do cloud based


testing
using any of the vendor commercial tool like sauce labs etc. It is
specified
clearly in the requirement that we need to test application in different
browsers
lets say 10 and different OS from XP to Macintosh etc. In this case
testing team
need to struggle a lot to get with the resources that are available for
them.
Imagine if the testing team has done projects only only windows none of
the team
memeber is aware of any other OS like Linux etc.In this situation team
should gain
some knowledge or at least using OS other than windows. So, in order to
handle
this kind of ambiguious situation it is best idea to use cloud based
testing. It
is also useful if the application need to be tested on browsers different
versions
then we can go with cloud based testing.

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.

Sauce labs platform is

- largest cloud for automated testing.


- Test web and mobile apps across over 385 configurations
- It uses industry standard WebDriver protocol
- It is having great stability and scale
- It can capture screencasts, log and test metadata

In order to test on Sauce labs trail version needs to be registered. Once


registering
on the sauce labs and getting access key for using sauce labs. Running
below script
on the our machine which connects to the sauce labs cloud with username
and access
key provided will allow us to test our application on cross browser and
cross platforms.

Ex :

final String USERNAME = "nanikumar.chalikonda";


final String ACCESS_KEY = "YOUR_ACCESS_KEY";
final String URL = "https://" + USERNAME + ":" + ACCESS_KEY +
"@ondemand.saucelabs.com:443/wd/hub";
// Getting the URL using username of sauce labs and access key

DesiredCapabilities caps = DesiredCapabilities.chrome();


// Using DesiredCapabilities class to choose the browser we need to run
test

caps.setCapability("platform", "Windows XP");


// Setting platform/OS to run browser
caps.setCapability("version", "43.0");
// version specifies the browser verision to run

WebDriver Chrome_Obj = new RemoteWebDriver(new URL(URL), caps);


// Creating object to RemoteWebDriver class
Chrome_Obj.get("https://www.google.co.in/?gws_rd=ssl");
// Hitting URL
System.out.println("title of page is: " + Chrome_Obj.getTitle());
// Getting title of the link we opened
Chrome_Obj.quit();
// Quitting object

For more information refer to this link https://wiki.saucelabs.com/

You might also like