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

Selenium Final

This document provides an introduction to Selenium, an open source tool for automating web application testing. It discusses what automation testing is and the benefits of Selenium. It then covers the different versions of Selenium including Selenium IDE, Selenium RC, Selenium Grid, and Selenium WebDriver. The document proceeds to provide information on installing and using Selenium IDE to record tests. It also covers locating elements and various Selenium commands.

Uploaded by

Bhavin Panchal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views

Selenium Final

This document provides an introduction to Selenium, an open source tool for automating web application testing. It discusses what automation testing is and the benefits of Selenium. It then covers the different versions of Selenium including Selenium IDE, Selenium RC, Selenium Grid, and Selenium WebDriver. The document proceeds to provide information on installing and using Selenium IDE to record tests. It also covers locating elements and various Selenium commands.

Uploaded by

Bhavin Panchal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

.

Selenium Documentation
Table of Contents

1. Introduction .................................................................................................................. 5
1.1 What is automation testing?.................................................................................................. 5
1.2 What is the use of automation testing? ................................................................................. 5
1.3 What we need to Automate? ................................................................................................. 6
1.4 When Automation is Not Recommended:.............................................................................. 6
1.5 What is Selenium? ............................................................................................................... 6
1.6 Advantages of Selenium ....................................................................................................... 7
1.7 What is the difference between Selenium and QTP .............................................................. 8
2. Different flavors of Selenium ........................................................................................ 9
2.1 Selenium-IDE ....................................................................................................................... 9
2.2 Selenium-RC........................................................................................................................ 9
2.3 Selenium-Grid ...................................................................................................................... 9
2.4 Selenium Web Driver/Selenium 2.0 .................................................................................... 10
3. Selenium IDE .............................................................................................................. 11
3.1 Installing Selenium IDE....................................................................................................... 11
3.2 Selenium IDE icons ............................................................................................................ 12
3.3 Recording your first test with Selenium IDE ........................................................................ 17
4. LOCATORS ................................................................................................................. 18
4.1 Tools to identify elements/objects ....................................................................................... 18
4.2 Firebug............................................................................................................................... 18
4.3 IE Developer tools .............................................................................................................. 22
4.3.1 Install Developer tool ..................................................................................................... 22
4.3.2 How to Install Debugbar ................................................................................................. 25
4.4 Google Chrome Developer tools ......................................................................................... 27
5. Locating Elements ...................................................................................................... 29
5.1 Locating elements by ID ..................................................................................................... 29
5.2 Finding elements by name .................................................................................................. 30
5.3 Finding elements by link text ............................................................................................... 30
5.4 XPATH Usage .................................................................................................................... 31
5.5 Finding elements by XPATH ............................................................................................... 33
5.5.1 Finding elements by XPATH and ID ................................................................................. 33
5.5.2 Finding elements by XPATH and NAME ........................................................................... 33
5.5.3 Finding elements by XPATH and LINK.............................................................................. 33
5.5.4 Partial match on attribute content.................................................................................. 34
5.6 Finding Elements by using CSS.......................................................................................... 35
6. IDE Context Menu ....................................................................................................... 37
6.1 Commands in Context Menu .............................................................................................. 37
6.2 Selenium Commands – “Selenese”..................................................................................... 44
6.2.1 Opening and Saving a Test Case ........................................................................ 47
6.3 Running Test Cases ........................................................................................................ 47
6.4 Analyzing the Results ......................................................................................................... 48

2
6.5 Working on pages with AJAX .............................................................................................. 48
6.6 Debugging.......................................................................................................................... 50
6.7 Synchronisation commands ................................................................................................ 51
6.8 Pausing test in the middle ................................................................................................... 52
6.9 Set/Clear Start Point ...................................................................................................... 52
6.10 Execute script from specific point............................................................................. 53
6.11 Creating test suites ..................................................................................................... 53
6.12 What we cannot record ................................................................................................... 54
6.13 GoBack .......................................................................................................................... 55
6.14 Refresh........................................................................................................................... 55
6.15 Enter key simulation ....................................................................................................... 55
6.16 MouseOver ..................................................................................................................... 56
6.17 Highlight ......................................................................................................................... 56
7. JAVA BASICS ............................................................................................................. 57
8. Selenium Remote Control........................................................................................... 63
8.1 What is Selenium Remote Control ...................................................................................... 63
8.2 Selenium RC ...................................................................................................................... 63
8.2.1 Selenium RC working: ............................................................................................ 63
8.3 Selenium RC Installation .................................................................................................... 65
8.3.1 Installing Selenium Server .................................................................................... 65
8.4 Running Selenium IDE tests with Selenium Remote Control ................................... 66
8.4.1 Getting Started with Selenium/ Selenium RC steps ..................................... 66
8.4.2 STEPS TO RUN SCRIPTS USING SELENIUM RC .............................................. 67
9. Programming your Tests ..................................................................................... 69
9.1 JAVA .................................................................................................................................. 69
9.2 Parameters....................................................................................................................... 70
10. Selenium Set up in Eclipse............................................................................ 71
10.1 Required Software ...................................................................................................... 71
10.2 Procedure ..................................................................................................................... 71
10.2.1 Create Java Project.............................................................................................. 73
10.2.2 Now need to create selenium server… .......................................................... 75
10.2.3 Your selenium server will be up and running…. ......................................... 76
10.2.4 Create Class ........................................................................................................... 76
11. Selenium Commands ...................................................................................... 77
11.1 Element Locator .......................................................................................................... 77
11.2 Important Selenium Commands ............................................................................... 78
12. Selenium Script Explanation ........................................................................ 79
13. JUNIT4................................................................................................................ 81
13.1.1 Annotations ............................................................................................................ 81
14. Selenium Commands ................................................................................................. 83
14.1 Use Attach Source to see the Selenium Driver Source Code ........................................... 86
14.2 Why should we do this? .................................................................................................. 88
14.3 How to find line numbers in Eclipse?............................................................................... 88

3
15. Sample Programs in RC for: ....................................................................................... 89
15.1 Text box ......................................................................................................................... 89
15.2 Link ................................................................................................................................ 89
15.3 Button............................................................................................................................. 90
15.4 Checkbox ....................................................................................................................... 90
15.5 Radio Button................................................................................................................... 90
15.6 Drop Down Box .............................................................................................................. 91
15.6.1 Select value .................................................................................................................... 91
15.6.2 Display all values ............................................................................................................ 92
15.6.3 Select values step by step ............................................................................................... 92
15.6.4 Write all values into NotePad/Excel/Wordpad. ............................................................... 92
15.7 Capture screen shot (positive) ........................................................................................ 93
15.8 Capture screen shot(with failure)..................................................................................... 93
15.9 Page scroll down using Java script ................................................................................. 94
15.10 Handle alerts .................................................................................................................. 94
15.11 How to read values from excel sheet............................................................................... 94
15.12 Create a Junit suite......................................................................................................... 95
15.13 Reports........................................................................................................................... 96
15.14 Tool tip ........................................................................................................................... 98
15.15 Handling Multiple windows and popups........................................................................... 98
15.16 Handling HTTPS sites..................................................................................................... 98
16. Selenium RC using TestNG ...................................................................................... 101
16.1 How to Install TestNG plugin in Eclipse ......................................................................... 101
16.2 TestNG sample script ................................................................................................... 101
16.3 Reports generation using TestNG ................................................................................. 103
16.4 Creating Test suites using TestNG ................................................................................ 103
17. Introduction to Web driver (Selenium 2.0)................................................................ 104
17.1 Introduction................................................................................................................... 104
17.2 Advantages over Selenium RC(1.0) .............................................................................. 104
17.3 How to setup Web driver using eclipse and Junit / TestNG ............................................ 104
17.4 More Ways to identify Elements .................................................................................... 105
17.5 Sample scripts .............................................................................................................. 106
18. Selenium Backed Web Driver ................................................................................... 108
19. Run Web Driver Scripts in Chrome .......................................................................... 111
20. Important Web Driver Commands ............................................................................ 114
21. Grid Using Web Driver .............................................................................................. 116

4
1. Introduction

1.1 What is automation testing?


Test automation has grown in popularity over the years because teams do not have the time or money
to invest in large test teams to make sure that applications work as they are expected to. Developers
also want to make sure that the code they have created works as they expect it to.

Developers use a multitude of different testing frameworks to test different aspects of the system.
Selenium is one of the most well-known testing frameworks in the world that is in use. It is an open
source project that allows testers and developers alike to develop functional tests to drive the browser.
It can be used to record workflows so that developers can prevent future regressions of code. Selenium
can work on any browser that supports JavaScript since Selenium has been built using JavaScript.

Software applications today are written as web-based applications to be run in an Internet browser. The
effectiveness of testing these applications varies widely among companies and organizations. In an era
of highly interactive and responsive software processes where many organizations are using some form
of Agile methodology, test automation is frequently becoming a requirement for software projects. Test
automation is often the answer. Test automation means using a software tool to run repeatable tests
against the application to be tested. For regression testing this provides that responsiveness.

1.2 What is the use of automation testing?


There are many advantages to test automation.

 Most are related to the repeatability of the tests and the speed at which the tests can be
executed.
 There are a number of commercial and open source tools available for assisting with the
development of test automation.
 Selenium is possibly the most widely-used open source solution.
 Frequent regression testing
 Rapid feedback to developers
 Virtually unlimited iterations of test case execution
 Support for Agile and extreme development methodologies
 Disciplined documentation of test cases
 Customized defect reporting
 Finding defects missed by manual testing

5
1.3 What we need to Automate?

It is not always advantageous to automate test cases. There are times when manual testing may be
more appropriate. For instance, if the application’s user interface will change considerably in the near
future, then any automation might need to be rewritten anyway.

1.4 When Automation is Not Recommended:

 Sometimes there simply is not enough time to build test automation.


 For the short term, manual testing may be more effective.
 If an application has a very tight deadline, there is currently no test automation available, and
it’s imperative that the testing get done within that time frame, then manual testing is the best
solution.

1.5 What is Selenium?


Selenium is a robust set of tools that supports rapid development of test automation for web-based
applications. Selenium provides a rich set of testing functions specifically geared to the needs of testing
of a web application. These operations are highly flexible, allowing many options for locating UI
elements and comparing expected test results against actual application behaviour.

Selenium: Selenium is a suite of tools to automate web app testing across many platforms.
Selenium...runs in many browsers and operating systems. Can be controlled by many programming
languages and testing frameworks.

* Create by developers at ThoughtWorks

* Released publically as an Open Source project on OpenQA

* Selenium is a test tool for web applications.

* Selenium tests run directly in a browser.

* Runs on Windows, Linux, and Macintosh.

* Runs in Internet Explorer, Mozilla and Firefox.

* Enables Browser Compatibility Testing.

* Enables System Functional Testing.

6
How it works:
 Uses JavaScript and Iframes in the browser
 Core runs the tests and interrogates the DOM
 RC server and Core communicate via AJAX
 Language hooks communicate with the RC server.

1.6 Advantages of Selenium

Below are the advantages of selenium

 Open source, Free software


 Easy Installation
 Easy Record and Play back
 Supports Multiple operating systems
 Supports Multiple Browser Testing
 Can convert scripts in to other languages (Java, C#, Python, Pearl etc...)
 Esay to learn
 Script once, Run on multiple browsers
 Testing tool for browser-based testing of web applications. It can be used both for functional,
compatibility (it has extensive cross-browser support) and regression testing.

Selenium is the best open source tool for doing automation for web based application and it does not
have any cost attached to it. The only cost is the effort which will go for designingand developing the
script for the application.There are Huge Openings in selenium because companies are trying to
migrate from QTP or commercial tools to Selenium – Open source tool.

There are a set of Selenium tools which when combined provides you the power to automate simple to
complex web application

7
1.7 What is the difference between Selenium and QTP

S.No Selenium QTP


1 Open source Commercial
2 Works on all OS Works on Windows only
3 Tests only Web applications Tests web and desktop
applications
4 Code can be converted to any one of languages such as Uses VB script
Java, C#, Ruby, Python, pearl, php etc
5 No object repository Has got an object repository
6 IDE sometimes does not record some fields Recording is a little reliable
events

8
2. Different flavors of Selenium

2.1 Selenium-IDE
 Selenium-IDE is the Integrated Development Environment for building Selenium test cases.
 It is Firefox add-on and provides an easy-to-use interface for developing and running individual
test cases or entire test suites.
 Selenium-IDE has a recording feature, which will keep account of user actions as they are
performed and store them as a reusable script to play back.
 It also has a context menu (right-click) integrated with the Firefox browser, which allows the
user to pick from a list of assertions and verifications for the selected location.
 Selenium-IDE also offers full editing of test cases for more precision and control.
 Although Selenium-IDE is a Firefox add-on, tests created in it can also be run against other
browsers by using Selenium-RC and specifying the name of the test suite on the command line.

2.2 Selenium-RC
 Selenium-RC allows the test automation developer to use a programming language for
maximum flexibility and extensibility in developing test logic.
 For instance, if the application under test returns a result set, and if the automated test program
needs to run tests on each element in the result set, the programming language’s iteration
support can be used to iterate through the result set, calling Selenium commands to run tests on
each item.
 Selenium-RC provides an API (Application Programming Interface) and library for each of its
supported languages: HTML, Java, C#, Perl, PHP, Python, and Ruby.

2.3 Selenium-Grid
 Selenium-Grid allows the Selenium-RC solution to scale for large test suites or test suites that
must be run in multiple environments.
 With Selenium-Grid, multiple instances of Selenium-RC are running on various operating system
and browser configurations;
 Each of these when launching register with a hub.
 When tests are sent to the hub they are then redirected to an available Selenium-RC, which will
launch the browser and run the test.
 This allows for running tests in parallel, with the entire test suite theoretically taking only as long
to run as the longest individual test.

9
2.4 Selenium Web Driver/Selenium 2.0
 Selenium 2.0 has many new exciting features and improvements over Selenium 1. 0
 The primary new feature is the integration of the WebDriver API. This addresses a number of
limitations along with providing an alternative, and simpler, programming interface.
 The goal is to develop an object-oriented API that provides additional support for a larger
number of browsers along with improved support for modern advanced web-app testing
problems.

10
3. Selenium IDE

3.1 Installing Selenium IDE


Pre Requisites:
 Mozilla Firefox

Installation:
 Go to http://seleniumhq.org/download/.
 Click on the download link for Selenium IDE. You may get a message saying Firefox prevented
this site (seleniumhq.org) from asking you to install software on your computer.
 Please click on the Allow button.
 A pop up will appear.
 Install button will become active and then click on it.
 This will now install the Selenium IDE as a Firefox add-on.
 Once the installation process is complete, it will ask you to restart Firefox.
 Click on the Restart button. Firefox will close and then reopen.
 Once the installation is complete, the Add-ons window will show the Selenium IDE and its
current version.

Start Selenium IDE:


1. Open a new Firefox browser
2. Click on tools
3. Click on Selenium IDE

11
3.2 Selenium IDE icons

 Base URL—This is the URL that the test will start. All open commands
will be relative to the Base URL unless a full path is inserted in the open
command.

 Speed Slider—This is the slider under the Fast Slow labels


on the screen.

 —Run all the tests in the IDE.

 —Run a single test in the IDE.

 —Pause a test that is currently running.

 —Step through the test once it has paused.


12
 —This is the record button. It will be engaged when the test is
recording.

 The Selenese Command select box has a list of all the commands that are
needed to create a test. You can type into it to use the auto complete
functionality or use it as a dropdown.
 Target textbox allows you to input the location of the element that you want
to work against.
 The Find button, once the target box is populated, can be clicked on to
highlight the element on the page.
 Value textbox is where you place the value that needs to change. For
example, if you want your test to type in an input box on the web page, you
would put what you want it to type in the value box.

 The Test table will keep track of all of your commands, targets, and values.
It has been structured this way because the original version of Selenium was
styled on FIT tests. The tests were originally designed to be run from HTML
files and the IDE keeps this idea for its tests. If you click on the Source tab,
you will be able to see the HTML that will store the test. Each of the rows will
look like:
o <tr>
o <td>open</td>
o <td>/chapter1</td>
o <td></td>
o </tr>
 The area below the Value textbox will show the Selenium log while the tests
are running. If an item fails, then it will have an [error] entry. This area will
also show help on Selenium commands when you are working in the
Command select box. This can be extremely useful when typing commands
into the Selenium IDE instead of using the record feature.

13
Important Icons in SIDE
 Base URL - This is the URL that the test will start.

 Fast Slow labels on the screen

 Run all the tests in the IDE.

 Run a single test in the IDE

 Pause a test that is currently running.

Important Icons in SIDE

 Step through the test once it has paused

 This is the record button

14
TEST CASE PANE:

Script will be displayed in testcase pane.

It has two tabs, one for displaying the command and their parameters in a
readable “table” format. The other tab - Source displays the test case in the
native format in which the file will be stored. By default, this is HTML
although it can be changed to a programming language such as Java or C#,
or a scripting language like Python.

The Command, Target, and Value entry fields display the currently selected
command along with its parameters. These are entry fields where you can
modify the currently selected command. The first parameter specified for a
command in the Reference tab of the bottom pane always goes in the Target
field. If a second parameter is specified by the Reference tab, it always goes
in the Value field. If you start typing in the Command field, a drop-down list
will be populated based on the first characters you type; you can then select
your desired command from the drop-down

15
LOG PANE:

LOG:
When you run your test case, error messages and information messages showing
the progress are displayed in this pane automatically, even if you do not first select
the Log tab. These messages are often useful for test case debugging. Notice the
Clear button for clearing the Log. Also notice the Info button is a drop-down
allowing selection of different levels of information to log.

Reference:
The Reference tab is the default selection whenever you are entering or modifying
Selenese commands and parameters in Table mode. In Table mode, the Reference
pane will display documentation on the current command.

16
3.3 Recording your first test with Selenium IDE

Steps:

1. Open URL www.google.com


2. Type “selenium” in search box
3. Click on search button
4. Click on first link in search results

17
4. LOCATORS

4.1 Tools to identify elements/objects


There are some tools to identify the elements

 Firebug
 IE DebugBar
 Google Chrome Developer Tools

Firebug: Firebug mostly used by web developers, as it allows developers to find


elements on the page by using the find functionality.

IE DebugBar: This is an add-on for IE. It also has many features like Firebug.

Google Chrome Developer Tools: This is not like IE or Firefox Google chrome
developer tools is built-in to the browser and will also allow you to find the
elements on the page and be able to work out its XPath.

4.2 Firebug
Firebug is an Add-on for FireFox.

To Install Firebug Open http://getfirebug.com/ in FireFox.

18
Click on Install Firebug

Click on the link “Firebug 1.6 for FireFox 3.6”

Click on firebug-1.6.2.xpi
Click Allow

19
Click on Install Now

Get a message “Restart Firefox to complete your changes.” Click on “Restart


Firefox”

After Restarting the browser, open www.google.com,

Right click on any element, we will get Inspect Element option shown below:

20
Click on Inspect Element, we will get locators of that element shown as below:

21
4.3 IE Developer tools

4.3.1 Install Developer tool


The Internet Explorer Developer Toolbar provides several features for exploring and
understanding Web pages. These features enable you to:

Locate and select specific elements on a Web page through a variety of techniques
View HTML object class names, ID's, and details such as link paths.

How to Install:
Go to below link
http://www.microsoft.com/download/en/details.aspx?id=18359

Click Download

You will get pop up window And select run option

22
After installing the Developer Toolbar, restart Internet Explorer and click the Developer Toolbar
icon in the command bar to display or hide the Developer Toolbar.

You can also open the View menu and then use the Explorer Bar menu. In Internet Explorer 7,
open the Tools menu and then use Toolbars->Explorer Bars to display or hide the Developer
Toolbar.

Snapsot of IE Developer tool:

23
In this picture u can see the HTML code of search text box.
Use the white arrow (mouse pointer) to select an object/element you can see the code. Short cut
for opening Developer tool is F12.

24
4.3.2 How to Install Debugbar

Open the URL: http://www.debugbar.com/

Go to Download Tab, Click on Download now

Save the “install-debugbar-v5.4.1.exe” file

Double click on the “install-debugbar-v5.4.1.exe” file, Get a popup “Please


CLOSE all your Internet Explorer windows before installing the Debug bar” Click on
OK

25
After installing the debug bar

Go to View menu --- > Tool bars ---- > select Debug bar

We will get the Debug bar below the Menu bar in Internet Explorer as shown below:

26
We will get the code of the element by dragging the “Drag target on document to
find element” as shown below:

4.4 Google Chrome Developer tools


No need to install any tool to identify objects. Developer tool is in built for Google Chrome.

Google Chrome Developer Tool is in built in the browser.

No need to install any tool for Google chrome.

To get the code of an element:

We will get Inspect element option by right click on the element as shown below:

27
You can see the code for the search box:

28
5. Locating Elements

Some Objects on web page:

 checkbox
 radio button
 link
 dropdown
 text field
 text area
 button

Examples of Elements on Html page:

 Input
 button
 form
 span
 ol
 ul
 a

Attributes for elements :

 name
 id
 href
 title
 value
 class

5.1 Locating elements by ID

Here i want to type so the command will be...

Type id=search

29
5.2 Finding elements by name

Find element by name:


I want to click on search button...below is the command..

The code for identify search box with NAME:

Type name=q

5.3 Finding elements by link text

Finding elements by link text:

link=Gear

30
5.4 XPATH Usage

There are times that you will need to find elements that are the same except for
the difference in one or two attributes. To handle this, we can add the attributes to
the query so that we can try to make the element more unique for use in the test.
The format can be used for any attribute on any element.

It will always follow the xpath=//element [@attribute='attribute


value'].

For example, if you have two div elements on the page but they only
differ by the class attribute, your XPath query would look like

xpath=//div[@class='classname'].

Xpath usage:

1. Two object has same attributes

<input id =123 name =456> textbox1

<button id =123 name =456>textbox2

2. The object attribute changing dynamically--facebook

3. Element has no attributes.

<input>

Syntax:

//--parent element

/child element

//element[@attribute='attribute name']

Example 1:

<input id =123 name =456> --textbox

<button id =123 name =456> --button

//button[@id='123']

31
Example 2:

<span id=456>

<input id =123 name =456> --textbox

<input id =123 name =456> --textbox

//span[@id-'456']/input[2]

Face book code:

<input type="submit" id="u119310_3" tabindex="4" value="Log In">

//input[@type='submit' and value='Log In']

u129747_3

u131602_3

Rightstart:

<a
href="http://www.rightstart.com/search/result/?link_location=default.leftnav&amp;
ocat=707" class="current">Travel Gear</a>

Using attribute:

//a[@href='http://www.rightstart.com/search/result/?link_location=default.leftnav&amp;ocat=707']

Using Prent element:

//dd[@class='last odd']/ol/li[3]/a

Example for Link:

<a href="http://www.rightstart.com/search/result/?link_location=default.leftnav&amp;ocat=707"
class="current">Travel Gear</a>

//a[@class='current'] --its not working

//a[@href='http://www.rightstart.com/search/result/?link_location=default.leftnav
&amp;ocat=707']

32
Xpath using position:

//element[@att='attname']/element1/element2

//dd[@class='last odd']/ol/li[10]/a

Dynamic element:

<input type="submit" id="u075656_3" tabindex="4" value="Log In"> --button


whihc id is dynamic

//element[@att='attname']

//input[@type='submit' and @value='Log In']

5.5 Finding elements by XPATH

Finding elements by XPATH:


 Finding elements by XPATH and ID
 Finding elements by XPATH and NAME
 Finding elements by XPATH and LINK
 Finding elements by XPATH and Text

5.5.1 Finding elements by XPATH and ID


Type //form[@id='search_mini_form']/div/input

5.5.2 Finding elements by XPATH and NAME


Type //input[@name='q']

5.5.3 Finding elements by XPATH and LINK


Click //a[@id='navigation-top-cat-label-707']

Click //ul[@id='nav']/li[3]/a

Click //a[@href='http://www.rightstart.com/search/result/?ocat=707']

33
5.5.4 Partial match on attribute content
There are times where only part of the ID is dynamic. For example, if you wanted to
access the element that has the text "This element has an ID that changes every
time the page is loaded" in it, you will use //div[contains(@id,'time_')]. This is due to
the first part of the ID always being static. The locator could also use starts-with instead
of contains to make the XPath query stricter in what is returned.

We can use two methods to find the elements with text

 Contains
 Starts-with

Syntax :

//element[text()='inner text'].

Example for Starts with: for link Booster seats

//a[starts-with(text(),'Boost')]

Example for contains: for link Car seat bases

//a[contains(text(), 'Seat')]

Finding elements by the text they contain can be quite useful when working with web
pages that have been created dynamically.

Contains:

If we know part of the text then we have to use this command.

Syntax:

//element[contains(text(),’inner text’)]

34
For the above example the command is :

//a[contains(text(),'Car Seat Bases')]

Starts with:

Syntax:

//element[starts with(text(),’inner text’)]

If we know the starting of the text then we have to use this command.

For the above example the command is:

//a[starts-with(text(),'Boost')]

5.6 Finding Elements by using CSS

locators are a way to tell selenium which specific element we want it to act on

Why CSS

 Because they are faster

 Because they are more readable

35
MORE READABLE:

//input[@id="myId"] vs css=input#myId

//input[@class="myClass"] vs css=input.myClass

//input[@name="myName"] vs css=input[name=myName]

//*[@id="myId"] vs css=#myId

//table[@id="myId"]//tr[@class="myClass"]//td[3] vs css=table#myId
tr.myClass td:nth(3)

36
6. IDE Context Menu

6.1 Commands in Context Menu


To open context menu, Start selenium IDE and right click on any opened firefox
browser, you can see the context menu.

 Assert
 Verify
 Wait For
 Store

37
Assert:
An “assert” will fail the test and abort the current test case

When we assert for an element it will returns Boolean value . True if the pattern
matches the text, false otherwise. Verifies that the specified text pattern appears
somewhere on the rendered page shown to the user.

38
Verify:
A “verify” will fail the test and continue to run the test case. True if the
pattern matches the text, false otherwise. Verifies that the specified text
pattern appears somewhere on the rendered page shown to the user.

39
Wait For:
Wait For Command will wait until specific time

40
Without waitFor command:-

With waitFor Command:

41
Store Element:
To Store Elements or the text on the web page . Sometimes there is a need to store
elements that are on the page to be used later in a test. This could be that your
test needs to pick a date that is on the page and use it later so that you do not
need to hardcode values into your test.

Once the element has been stored, you will be able to use it again by requesting it
from a JavaScript dictionary that Selenium keeps track of. To use the variable, it
will take one of the following two formats: it can look like ${variableName} or
storedVars['variableName']. I prefer the storedVars format, as it follows the same
format because it is within Selenium internals.

To see how this works, let's work through the following example:
 Open the Selenium IDE and switch off the Record button.
 Right-click on the text Assert that this text is on the page, go to the
storeText command in the context menu, and click on it. If it does not
display there, go to Show all Available Commands and click on it there.
 A dialog will appear similar to the next screenshot. Enter the name of a
variable that you want to use. I have used textOnThePage as the name of my
variable

 Click on the row below the storeText command in Selenium IDE.


 Type the command type into the Command textbox.
 Type storeinput into the target box.
 Type javascript{storedVars['textOnThePage'];} into the value box.
 Run the test.

42
43
6.2 Selenium Commands – “Selenese”
Selenium commands, often called selenese, are the set of commands that run your
tests. A sequence of these commands is a test script

A command is what tells Selenium what to do. Selenium commands come in three
“flavors”: Actions, Accessors and Assertions.

Actions are commands that generally manipulate the state of the application. They
do things like “click this link” and “select that option”. If an Action fails, or has an
error, the execution of the current test is stopped.

Many Actions can be called with the “AndWait” suffix, e.g. “clickAndWait”. This
suffix tells Selenium that the action will cause the browser to make a call to the
server, and that Selenium should wait for a new page to load.

Accessors examine the state of the application and store the results in variables,
e.g. “storeTitle”. They are also used to automatically generate Assertions.

Assertions are like Accessors, but they verify that the state of the application
conforms to what is expected. Examples include “make sure the page title is X” and
“verify that this checkbox is checked”.

All Selenium Assertions can be used in 3 modes: “assert”, “verify”, and ”


waitFor”. For example, you can “assertText”, “verifyText” and
“waitForText”. When an “assert” fails, the test is aborted. When a “verify”
fails, the test will continue execution, logging the failure.

Editing a test case:

Insert Command:

Table View:

Select the point in your test case where you want to insert the command. To do
this, in the Test Case Pane, left-click on the line where you want to insert a new
command

Insert Comment:
Comments may be added to make your test case more readable. These comments
are ignored when the test case is run

44
Select the line in your test case where you want to insert the comment. Right-click
and select Insert Comment. Now use the Command field to enter the comment.
Your comment will appear in purple font

45
Souse view:

Select the point in your test case where you want to insert the comment. Add an
HTML-style comment, i.e., <!-- your comment here -->.

Edit a Command or Comment


Table View

Simply select the line to be changed and edit it using the Command, Target,
and Value fields

46
6.2.1 Opening and Saving a Test Case
Like most programs, there are Save and Open commands under the File menu.
When you open an existing test case or suite, Selenium-IDE displays its Selenium
commands in the Test Case Pane.

6.3 Running Test Cases

The IDE allows many options for running your test case. You can run a test
case all at once, stop and start it, run it one line at a time, run a single
command you are currently developing, and you can do a batch run of an
entire test suite. Execution of test cases is very flexible in the IDE.

Run a Test Case


Click the Run button to run the currently displayed test case.
Run a Test Suite
Click the Run All button to run all the test cases in the currently loaded
test suite.
Stop and Start
The Pause button can be used to stop the test case while it is running.
The icon of this button then changes to indicate the Resume button. To
continue click Resume.
Stop in the Middle
You can set a breakpoint in the test case to cause it to stop on a
particular command. This is useful for debugging your test case. To set
a breakpoint, select a command, right-click, and from the context
menu select Toggle Breakpoint.
Start from the Middle
You can tell the IDE to begin running from a specific command in the
middle of the test case. This also is used for debugging. To set a
startpoint, select a command, right-click, and from the context menu
select Set/Clear Start Point.
Run Any Single Command
Double-click any single command to run it by itself. This is useful when
writing a single command. It lets you immediately test a command you
are constructing, when you are not sure if it is correct. You can
double-click it to see if it runs correctly. This is also available from the
context menu.

47
6.4 Analyzing the Results

 From Table view, observe the green vs. red shading.


 From Table or Source view, select the Log tab and look for errors (bold red
font)..

6.5 Working on pages with AJAX

 Asynchronous JavaScript and XML


 AJAX is not a new programming language, but a new way to use
existing standards.
 AJAX is the art of exchanging data with a server, and update parts of
a web page - without reloading the whole page.
 AJAX is a technique for creating fast and dynamic web pages.
Start Selenium IDE
Record some steps – run the script. It fails some where then,

 Right-click on the step that failed so that the Selenium IDE context menu
appears.
 Click on Insert New Command.
 In the Command select box, type waitForElementPresent or select it from
the drop-down list.
 In the Target box, add the target that is used in the verifyText command.
 Run the test again, and it should pass this time

The following commands make up the waitFor set of commands, but this is not an
exhaustive list:
waitForAlertNotPresent
waitForAlertPresent
waitForElementPresent
waitForElementNotPresent
waitForTextPresent
waitForTextNotPresent
waitForPageToLoad
waitForFrameToLoad
48
49
6.6 Debugging
We have successfully created a number of tests and have seen how we can work
against AJAX applications, but unfortunately creating tests that run perfectly first
time can be difficult. Sometimes, as a test automater, you will need to debug your
tests to see what is wrong.
These two steps are quite useful when your tests are not running and you want to
execute a specific command.
 Highlight a command.
 Press the X key: This will make the command execute in the Selenium IDE

highlight(locator)
Arguments:

 locator - an element locator

Briefly changes the backgroundColor of the specified element yellow. Useful


for debugging.
Find:

Find is a button in selenium IDE. Which is used to find the element.

50
6.7 Synchronisation commands

waitFor and Pause Both are synchronization commands.

waitForPageToLoad(timeout)
Arguments:

 timeout - a timeout in milliseconds, after which this command will


return with an error

Waits for a new page to load.

You can use this command instead of the "AndWait" suffixes, "clickAndWait",
"selectAndWait", "typeAndWait" etc. (which are only available in the JS API).

Selenium constantly keeps track of new pages loading, and sets a


"newPageLoaded" flag when it first notices a page load. Running any other
Selenium command after turns the flag to false. Hence, if you want to wait
for a page to load, you must wait immediately after a Selenium command
that caused a page-load.

Pause:

pause(waitTime)

Arguments:

 waitTime - the amount of time to sleep (in milliseconds)

Wait for the specified amount of time (in milliseconds).

Difference

If pages loads before the time it will continue to next step.

Pause:---Will pause test until the specified time

51
6.8 Pausing test in the middle

If you want to pause test case in middle follow the below steps:

Let’s say there are 6 commands in your script and you want to pause your script at
3rd command.

Right click on command 3 and select Toggle/Break Point. Automatically you can see
pause symbol in the test case pane. Your test will be paused at command 3. If you
want to remove the pause repeat the same step. Pause symbol should be removed.

6.9 Set/Clear Start Point

If you want to execute a script from middle follow below steps:

52
Let’s say there are 6 commands in your script and you want to start your script
from 3rd command.

Right click on command 3 and select set/clear start point. Automatically you can
see RUN Symbol in the test case pane. If you start running the script. Your test will
be start running from command 3. If you want to remove the start point repeat the
above step. RUN symbol should be removed.

6.10 Execute script from specific point


If you want to execute a single command in script from middle follow below steps:

Let’s say there are 6 commands in your script and you want to execute 3 rd
command.

Right click on command 3 and select Execute this command. Automatically that
command will be executed. Or you can double click on that command. Command
will be executed.

6.11 Creating test suites

A test suite is a collection of tests. When using Selenium-IDE, test suites also can
be defined using a simple HTML file. An HTML table defines a list of tests where
each row defines the filesystem path to each test. An example tells it all.

The Test suite that contains One.html and Two.html

To create a test suite in Selenium IDE:

1. Open Selenium IDE

2. Go to File>New Test Suite

3. To add test cases: Go to File>Add test case

4. Navigate to the location of your test case

5. Click on Add

6. Repeat steps 3-5 for more test cases

The Test suite that contains One.html and Two.html

 Go to File>Save Test Suite


 Enter a file name
53
 Click on Save

When the Run Entire Test Suite button is clicked, it will run all the tests in the
test suite. It will log all the passes and failures at the bottom of the Test Case box.

To save this, click on the File menu and then click on Save Test Suite and save
the Test Suite file to somewhere convenient.

6.12 What we cannot record


Unfortunately, there are a number of things that Selenium cannot do. Since
Selenium was developed in JavaScript, it tries to synthesize what the user does
with JavaScript events.
 Silverlight and Flex/Flash applications, cannot be recorded with Selenium
IDE.
 Selenium cannot do file downloads.

Questions

 What is the main language that drives Selenium IDE?


o . Answer: JavaScript
 . Selenium IDE works on Internet Explorer?
o . Answer: False
 . Selenium verifies items on the page when it is recording steps?
o . Answer: False
 . What is the difference between verify and assert?
o . Answer: A verify command validates and verifies that an element
is on the page but does not interrupt the execution of the test. Assert
is similar to a verify command except that it will cause the test to fail
and interrupt its execution.
 . If you wanted to validate that a button has appeared is on a page which
two commands would be the best to use?
o . Answer: verifyElementPresent/assertElementPresent

54
 If an element got added after the page has loaded what command would
you use to make sure the test passed in the future?
o . Answer: waitForElementPresent
 . How do we run all the tests in a Test Suite?
o . Answer: Click on the button with the Arrow and three solid green
lines

6.13 GoBack

Go Back:

If user clicks Back button of the Browser, then we need to use below command

Syntax:-

goBack()

Simulates the user clicking the "back" button on their browser

6.14 Refresh

If the user wants to press the refresh key or button in browser.

Syntax:

refresh()

Simulates the user clicking the "Refresh" button on their browser.

6.15 Enter key simulation

Enter
If user press Enter button from key board, then we need to use below command.

Syntax:-

keyPress(locator, keySequence)

55
Arguments:

- an element locator

- Either be a string("\" followed by the numeric keycode of the key to be pressed,


normally the ASCII value of that key), or a single character. For example: "w", "\119".

Simulates a user pressing and releasing a key.

6.16 MouseOver

Mouse Over:

If a user hover the mouse on an element

Syntax:

mouseOver(locator)

Arguments:

- an element locator

6.17 Highlight
Highlight:
If you want to execute specific step
Syntax:
highlight(locator)

Arguments:
locator - an element locator

Briefly changes the background Color of the specified element yellow. Useful for debugging.

Find

56
7. JAVA BASICS

Below are some basics of JAVA useful for Selenium scripts:

Class
Method
Object
Sample program
Variables
Creating Objects
If conditions
For loops
Extending class
Arrays

Class:

A class is nothing but a blueprint or a template for creating different objects which
defines its properties and behaviors. Java class objects exhibit the properties and
behaviors defined by its class. A class can contain fields and methods to describe
the behavior of an object.

Method:

Methods are nothing but members of a class that provide a service for an object or
perform some business logic. Java fields and member functions names are case
sensitive. Current states of a class’s corresponding object are stored in the object’s
instance variables. Methods define the operations that can be performed in java
programming.

Objects:

An object is an instance of a class created using a new operator. The new


operator returns a reference to a new instance of a class. This reference can
be assigned to a reference variable of the class. The process of creating
objects from a class is called instantiation. An object encapsulates state and
behavior.

57
An object reference provides a handle to an object that is created and stored
in memory. In Java, objects can only be manipulated via references, which
can be stored in variables

Sample program:

IF CONDITIONs:

if(Boolean-Expression){
//Executes if Boolean expression is true
}
else{
//Executes if Boolean expression is false
}

For Loop in Java

The for loop is the type of looping construct. It also works as while loop construct
but it provide the initialization, condition and the increment is same written in the
for construct. All the statements which has to be executed written in the for block.

for( initialization; termination; increment)


{
statements;
}

package com.devmanuals2;

public class ForExample {

public static void main(String[] args) {


int i;
for(i=1;i<=5;i++){
System.out.println(i+" Times");
}

Variables:

58
A variable is a container that stores a meaningful value that can be used
throughout a program. For example, in a program that calculates tax on items you
can have a few variables - one variable that stores the regular price of an item and
another variable that stores the total price of an item after the tax is calculated on
it. Variables store this information in a computer's memory and the value of a
variable can change all through out a program.

Declaring and defining variables


Before using variables you must declare the variables name and type. See
the following example for variables declaration:

int num; //represents that num is a variable that can store value of int
type.
String name; //represents that name is a variable that can store string
value.
boolean bol; //represents that bol is a variable that can take boolean
value (true/false);

You can assign a value to a variable at the declaration time by using an


assignment operator ( = ).

int num = 1000; // This line declares num as an int variable which holds
value "1000".
boolean bol = true; // This line declares bol as boolean variable which is
set to the value "true".

Example program:

class PrintText

public static void main(String[] args){

//declare some variables

byte aByte = -10;

int aNumber = 10;

char aChar = 'b';

boolean isBoolean = true;

//print variables alone

59
System.out.println(aByte);

System.out.println(aNumber);

//print variables with text

System.out.println("aChar = " + aChar);

System.out.println("Is the isBoolean variable a boolean variable? " + isBoolean);

EXTENDS:

You extend a class by using the extends keyword in a class declaration,

The Parent class

public class Parent {


}

The Child class

public class Child extends Parent {


}

In java, there's the very important “extend” keyword.

A class declaration can use the extend keyword on another class, like this:
class C extends B { … } .

When a class C extends class B, C automatically has all variables and


methods defined in class B. (think of it as a internal copying mechanism)

If class C defines a variable or method that has the same name in class B,
class C's definition overrides B's.

class B {
int x;
void setIt (int n) { x=n;}
void increase () { x=x+1;}
void triple () {x=x*3;};

60
int returnIt () {return x;}
}

class C extends B {
void triple () {x=x+3;} // override existing method
void quadruple () {x=x*4;} // new method
}

public class GetRich {


public static void main(String[] args) {
B b = new B();
b.setIt(2);
b.increase();
b.triple();
System.out.println( b.returnIt() ); // prints 9

C c = new C();
c.setIt(2);
c.increase();
c.triple();
System.out.println( c.returnIt() ); // prints 6
}
}

In the above code, class C inherits all class B's variables and methods. Class
C overrides the “triple” method, and added a “quadruple” method.

Other classes can extend Class C, as to inherit all members and methods of
class C (which includes those in B). In this way, a tree hierarchy is formed.

When class C extends B, we say that C is a “subclass” of B, and B is the


“superclass” of C. This is called inheritence, because C inherited from B. Two
or more classes can inherit from the same parent class. However, a class
can only have one parent.

In Java, EVERY class is a subclass of java.lang.Object (or subclass of its


subclasses). Every class in Java is a node on this giant tree.

ARRAYS:

An array is a container object that holds a fixed number of values of a single


type. The length of an array is established when the array is created. After
creation, its length is fixed. You've seen an example of arrays already, in the
main method of the "Hello World!" application. This section discusses arrays
in greater detail.

61
An array of ten elements

Each item in an array is called an element, and each element is accessed by


its numerical index. As shown in the above illustration, numbering begins
with 0. The 9th element, for example, would therefore be accessed at index
8.

An array is a very common type of data structure where in all elements


must be of the same data type.

Once defined , the size of an array is fixed and cannot increase to


accommodate more elements.

The first element of an array starts with zero

62
8. Selenium Remote Control

8.1 What is Selenium Remote Control


 Selenium-RC allows the test automation developer to use a programming
language for maximum flexibility and extensibility in developing test logic.
 For instance, if the application under test returns a result set, and if the
automated test program needs to run tests on each element in the result set,
the programming language’s iteration support can be used to iterate through
the result set, calling Selenium commands to run tests on each item.
 Selenium-RC provides an API (Application Programming Interface) and
library for each of its supported languages: HTML, Java, C#, Perl, PHP,
Python, and Ruby.

8.2 Selenium RC
Selenium RC Including support for several languages (Java, Javascript,
PRuby, HP, Python, Perl and C#) and support for almost every browser.

8.2.1 Selenium RC working:

Selenium RC components:

 Selenium Server
 Client libraries

The Selenium Server which launches and kills browsers.

Client libraries which provide the interface between each programming language
and the SeleniumRC Server.

63
Client libraries communicate with the Server passing each Selenium command
for execution. Then the server passes the Selenium command to the browser
using Selenium-Core JavaScript commands. The browser, using its JavaScript
interpreter, executes the Selenium command.This runs the Selenese action or
verification you specified in your test script.

64
8.3 Selenium RC Installation

• Install the Selenium RC Server.

• Set up a programming project using a language specific client driver

8.3.1 Installing Selenium Server


The Selenium RC server is simply a Java jar file (selenium-server.jar), which
doesn’t require any special installation. Just downloading the zip file and extracting
the server in the desired directory is sufficient.

• Go to http://seleniumhq.org/download/.
• Under Selenium Server (formerly the Selenium RC Server) section
you can see the selenium server latest version.
• Click on download, it will be redirected to selenium server download
page.
• Selenium server is a JAR file. Download selenium-server-
standalone-2.ob3.jar

Create a Folder selenium in “C” drive.


Paste the selenium-server-standalone-2.ob3.jar file in that folder.

We need to be able to start and stop the Selenium Server.

We can do this at the command line:


Start: (Command line)

java -jar selenium-server-standalone-2.0b3.jar

The output should appear similar to the following screenshot

65
Stop: (Browser)

http://localhost:4444/selenium-
server/driver/?cmd=shutDownSeleniumServer

8.4 Running Selenium IDE tests with Selenium Remote Control


Imagine that you have to run your Selenium IDE tests on a computer that doesn't have
Selenium IDE installed or you do not want to use Firefox with any add-ons installed. To
do this you will need to use Selenium Remote Control.

8.4.1 Getting Started with Selenium/ Selenium RC steps

1. Record your test case using Selenium IDE

2. Play your test case using selenium IDE itself to make sure
that your test case works.
66
3. Export your recording test case - as html file.
4. Create a test suite.
5. Run your exported html test case using selenium rc

8.4.2 STEPS TO RUN SCRIPTS USING SELENIUM RC

Create folders:
Create a folder in any drive – Ex: C:\tests
Create a folder in any drive – Ex: C:\results
We need to create two folders.
1. To save our test suite and test case. (tests)
2. To save results (results)
Using Selenium IDE record a test case and save it as .html in a tests folder.
Make sure your test run correctly.
Create a Test suite:
Create a test suite and save it in C:\tests folder
To run our tests in Selenium Remote Control we will have to use the –htmlsuite
argument. This tells Selenium to open the Test Suite that we created. We then
need to tell it where to find the Test Suite and then where to write the results to.
Our command in Command Prompt or a console window will be similar to the
following snippet:
We can run our tests in any browser by using selenium RC.

Synatx:

java -jar selenium-server.jar -htmlSuite "*browser"


"http://www.example.com" "target folder" "results folder“

RUN THE ABOVE COMMAND FROM COMMAND PROMPT

Run this command from selenium directory.

Example:

C:\s0elenium>java -jar selenium-server.jar -htmlSuite "*iexplore"


"http://www.google.com" "c:\tests\run.html“ "c:\results\results1.html"

67
Below is the screenshot of TEST RUNNER

RESULTS:

68
9. Programming your Tests

There are essentially two tasks:


• Generate your script into a programming language from Selenium-IDE, optionally
modifying the result.
• Write a very simple main program that executes the generated code.
Optionally, you can adopt a test engine platform like JUnit or TestNG for Java, or
NUnit for .NET if you are using one of those languages.
Here, we show language-specific examples. The language-specific APIs tend to
differ from one to another, so you’ll find a separate explanation for each.
• Java
• C#
• Python
• Ruby
• Perl, PHP

9.1 JAVA
For Java, we need to use either JUnit or TestNG as the test engine. Some
development environments like Eclipse have direct support for these via plug-ins.
This makes it even easier.
You will probably want to rename the test class from “NewTest” to something of
your own choosing.

Also, you will need to change the browser-open parameters in the statement

selenium = new DefaultSelenium("localhost", 4444, "*iehta", "http://www.google.com/");


The Selenium-IDE generated code will look like this. This example has comments
added manually for additional clarity.

package com.example.tests;
// We specify the package of our tests
import com.thoughtworks.selenium.*;
// This is the driver’s import. You’ll use this for instantiating a
// browser and making it do what you need.
import java.util.regex.Pattern;
// Selenium-IDE add the Pattern module because it’s sometimes used for
// regex validations. You can remove the module if it’s not used in your
// script.
public class NewTest extends SeleneseTestCase {
// We create our Selenium test case
public void setUp() throws Exception {
setUp( "http://www.google.com/" , "*firefox" );
// We instantiate and start the browser
}

69
public void testNew() throws Exception {
selenium.open( "/" );
selenium.type( "q" , "selenium rc" );
selenium.click( "btnG" );
selenium.waitForPageToLoad( "30000" );
assertTrue(selenium.isTextPresent( "Results * for selenium rc" ));
// These are the real test steps
}
}

9.2 Parameters

The parameters required when creating the browser instance are:

host Specifies the IP address of the computer where the server is located. Usually,
this is the same

machine as where the client is running, so in this case localhost is passed.

port Specifies the TCP/IP socket where the server is listening waiting for the client
to establish a connection.

browser The browser in which you want to run the tests. This is a required
parameter.

url The base url of the application under test. This is required by all the client libs
and is integralinformation for starting up the browser-proxy-AUT communication.

70
10. Selenium Set up in Eclipse
This section will explain how to set up selenium in Eclipse.

10.1 Required Software


Achala Solutions will deliver the work in four phases as listed below. Each of the
phases and activities are described in the following picture

 Eclipse (Version 3.5.2) –


http://www.eclipse.org/downloads/download.php?file=/eclipse/do
wnloads/drops/R-3.5.2-201002111343/eclipse-SDK-3.5.2-win32.zip

 Jdk 1.5.0_11 or above


http://java.sun.com/javase/downloads/index_jdk5.jsp
 4 Jar files (junit-4.5, jxl, selenium-java-client-driver, selenium-
server)

10.2 Procedure

1. Create an empty folder (Selenium_Scripts1) in F drive-no need to create in F


drive you can create folder in any folder.

2. Create an empty folder lib in Selenium_Scripts1 folder.

3. Install jdk1.5.0_11, copy the jdk1.5.0_11 folder which is in c folder


(Generally it will be installed in “C” Drive-- C:\Program Files\Java) and paste
it in Selenium_Scripts1 folder.

4. Paste the 4 Jar files (junit-4.5, jxl, selenium-java-client-driver, and selenium-


server) in lib folder.

5. Open eclipse (F: \eclipse\eslipse.exe)

You will get the below window select the path (F:\ Selenium_Scripts1) which you
created a folder earlier in F drive.

71
After clicking Ok you will get below screen select “work bench”.

72
You will get the below screen—eclipse environment.

10.2.1 Create Java Project

1. File—New—Java Project

2. Give Project name (Selenium_scripts)

3. Click Configure JREs in that screen. You will get a new window.

4. Click Add—Standard VMnext.

JRE Home—we need to specify path.

Click directory—browse the path where you created the folder


(F:\Selenium_scripts1\jdk1.5.0_11\jre)

All jar files will be added.. click Finish and click OK

Click finish on the open window (New Java Project window)

You can see the new project Selenium_scripts in eclipse window.

73
New Java Project with all jar files.

Now Right click on JRE System Library[Java SE-1.6]

Select Build Path-configure Build Path.

A new window will be opened. Select Libraries tab and click Add External Jars
Button.

Select path F:\demo\lib and select all 4 Jar files click OK.

You can see all Jar files under Libraries Tab.

Click Ok.

74
You can see the Referenced Libraries…

Everything is done.

10.2.2 Now need to create selenium server…


Go to RUNExternal ToolsExternal tools configuration…

There click Program---u will get new configuration window.

Give name selenium server (any name you can give).

Location ---click on Browse file systems.


F:\Selenium_Scripts1\jdk1.5.0_11\bin\java.exe

Working Directory--- Browse file system --- F:\ Selenium_Scripts1\lib.

Arguments - -jar selenium-server.jar

Click Apply and Run….


75
10.2.3 Your selenium server will be up and running….

Now you can write your scripts and Enjoy Selenium Automation….

10.2.4 Create Class

File – New –class

Give Name First and click the check box public static void main (String []
args) click Finish

76
11. Selenium Commands

11.1 Element Locator


Element Locators tell Selenium which HTML element a command refers to.

The format of a locator is: locatorType=argument

Example: - (“link=click”)

Selenium supports the following strategies for locating elements:

id=id
Select the element with the specified @id attribute
name=name
Select the first element with the specified @name attribute.

 username
 name=username

xpath=xpathExpression
Locate an element using an XPath expression.

 xpath=//img[@alt='The image alt text']


 xpath=//table[@id='table1']//tr[4]/td[2]

link=textPattern
Select the link (anchor) element which contains text matching the specified
pattern.

 link=The link text

77
11.2 Important Selenium Commands

Command Usage Description


start() selenium.start(); Launches the browser with a new
Selenium session
stop() selenium.stop(); Ends the current Selenium
testing session (normally killing
the browser)
click() selenium.click("link=Home"); Clicks on a link, button, checkbox
selenium.click("name=send"); or radio button. If the click action
causes a new page to load (like a
link usually does), call
waitForPageToLoad.
type() Type( Sets the value of an input field,
string locator, as though you typed it in. Can
string value); also be used to set the value of
combo boxes, check boxes, etc.
selenium.type("name=logi In these cases, value should be
n[username]", ndasam); the value of the option selected,
not the visible text.

check() Check( Check a toggle-button


string locator); (checkbox/radio)
selenium.check ("guest”);
uncheck() Uncheck( Uncheck a toggle-button
string locator); (checkbox/radio)
select() Select( Select an option from a drop-
string selectLocator, down using an option locator.
string optionLocator);
selenium.select("payware_
expiration_yr",
"label=2010”);

For more commands please refer the link

http://release.seleniumhq.org/selenium-remote-
control/0.9.2/doc/java/com/thoughtworks/selenium/Selenium.html

78
12. Selenium Script Explanation
Here we can see the code for simple login and logout functionality with comments
and the explanation of code.

Here is the sample script which will open a page...

This script was written using JUnit...

import org.junit.After; //Junit package


import org.junit.Before; //Junit package
import org.junit.Test; //Junit package
import org.openqa.selenium.server.SeleniumServer; //Selenium server package

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestCase;
import com.thoughtworks.selenium.Selenium;

public class Google1 extends SeleneseTestCase { //Class name[class name should


be same as program name]

private Selenium selenium;


private SeleniumServer seleniumServer;

@Before
public void setUp() throws Exception { //Set UP method to start selenium and
selenium server

/*Defining the selenium method.

DefaultSelenium selenium=new
DefaultSelenium("localhost",4444,"*iehta","http://");

localhost—serverHost

4444 --- serverport

Iehta(IE) or iexplore(IE) or firefox----- browserstart command(we can use *firefox


also)

79
http:// ---browser URL(Here we can give full URL of site) */
selenium = new DefaultSelenium("localhost", 4444, "*iehta", "http://");
seleniumServer = new SeleniumServer();
seleniumServer.start();
selenium.start();
}

@Test ---//Our actual test case steps come here


public void testText1() throws Exception {
selenium.open("http://www.yahoo.com");
selenium.windowMaximize();
}
@After // To stop selenium and selenium server
public void tearDown() throws Exception {
selenium.stop();
seleniumServer.stop();
}
}

80
13. JUNIT4

JUnit 4.x is a test framework which uses annotation to identify the methods which
contain tests. JUnit assumes that all test methods can be performed in an arbitrary
order. Therefore tests should not depend other tests. To write a test with JUnit

13.1.1 Annotations
Annotation Description
@Test public void method() Annotation @Test identifies that this
method is a test method.
@Before public void method() Will perform the method() before each
test. This method can prepare the test
environment, e.g. read input data,
initialize the class)
@After public void method() Test method must start with test
@BeforeClass public void method() Will perform the method before the start
of all tests. This can be used to perform
time intensive activities for example be
used to connect to a database
@AfterClass public void method() Will perform the method after all tests
have finished. This can be used to
perform clean-up activities for example
be used to disconnect to a database

@Test
Mark your test cases with @Test annotations. You don’t need to prefix your
test cases with “test”. In addition, your class does not need to extend from
“TestCase” class.

@Test
public void addition() {
assertEquals(12, simpleMath.add(7, 5));
}

@Before and @After


Use @Before and @After annotations for “setup” and “tearDown” methods
respectively. They run before and after every test case.

81
@Before
public void runBeforeEveryTest() {
simpleMath = new SimpleMath();
}

@After
public void runAfterEveryTest() {
simpleMath = null;
}

@BeforeClass and @AfterClass


Use @BeforeClass and @AfterClass annotations for class wide “setup” and
“tearDown” respectively. Think them as one time setup and tearDown. They
run for one time before and after all test cases.

@BeforeClass
public static void runBeforeClass() {
// run for one time before all test cases
}

@AfterClass
public static void runAfterClass() {
// run for one time after all test cases
}

82
14. Selenium Commands

Text box:
selenium.type("locator", "text");

Type:

Sets the value of an input field, as though you typed it in.

Parameters:
locator an element locator
value the value to type

Link/button/Check box/Radio button:


selenium.click("link=linktext");

Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually
does), call waitForPageToLoad.

Parameters:
locator an element locator

Drop Down Box:

a) Select value:
selenium.select("locaotr", "lable=value");
Select an option from a drop-down using an option locator.
Parameters:
selectLocator an element locator identifying a drop-down menu
optionLocator an option locator (a label by default)

b) Display all values:

selenium.getSelectOptions(selectLocator)

Gets all option labels in the specified select drop-down.

Parameters:
selectLocator an element locator identifying a drop-down menu
Returns:
an array of all option labels in the specified select drop-down

83
Multiselect --List box

selenium.addSelection(locator, optionLocator);

Add a selection to the set of selected options in a multi-select element using an option locator.

Parameters:
locator an element locator identifying a multi-select box
optionLocator an option locator (a label by default)

selenium.removeSelection(locator, optionLocator);

Remove a selection from the set of selected options in a multi-select element using an option locator.

Parameters:
locator an element locator identifying a multi-select box
optionLocator an option locator (a label by default)

Capture screen shot(positive):


selenium.captureScreenshot(filename);

Captures a PNG screenshot to the specified file.

Parameters:
filename the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"

selenium.captureEntirePageScreenshot(filename, kwargs);
Saves the entire contents of the current window canvas to a PNG file. Parameters:
filename the path to the file to persist the screenshot as. No filename extension will be appended by
default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by
native code.
kwargs a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD"
. Currently valid options:

background
the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-
than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension
to fail and a black background is exposed (possibly obscuring black text).

Capture screen shot(with failure)


public Scroll()
{
setCaptureScreenShotOnFailure(true);

84
}

How to use Java script in selenium:


selenium.getEval(javascript);

Gets the result of evaluating the specified JavaScript snippet. The snippet may have multiple lines, but only the result
of the last line will be returned.

Parameters:
script the JavaScript snippet to run
Returns:
the results of evaluating the snippet

Page scroll down using Java script:


selenium.getEval("window.scrollBy(0,500)");

Scrolls down the page 500 pixles.

Alerts
Normal alerts
selenium.getAlert();

Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.

Returns:
The message of the most recent JavaScript alert

On load alerts: This can be handled by using Selenium 2

Handling Multiple windows and popups


Extracting window IDs with Selenium :
selenium.getAllWindowIds();

Returns the IDs of all windows that the browser knows about.

Returns:
the IDs of all windows that the browser knows about.

selenium.getAllWindowNames();

Returns the Namess of all windows that the browser knows about.

Returns:
the NAMESs of all windows that the browser knows about.

selenium.getAllWindowTitles();

Returns the Titles of all windows that the browser knows about.

85
Returns:
the Titles of all windows that the browser knows about.

Tabbed browsing and handling tabs with selenium RC


Handling popups/new windows, performing actions in pop up window
Closing pop up windows

14.1 Use Attach Source to see the Selenium Driver Source Code

The first thing we will do is configure Eclipse to let us see the source code for the Selenium Driver.

You should see a Class File Editor window, with the message "Source not found". This is because we
haven’t tol d Eclipse where the source code for the Selenium Java Driver and Server resides on the disk.

We can easily fix this by pressing the [Attach Source. . . ] button and navigating to the source code .jar
file

• selenium-java-2.X-srcs.jar

86
87
14.2 Why should we do this?
With Eclipse setup like this, we can start to understand the code that we are using. It is very important
to understand as much as

possible about the libraries and classes that you are using in your testing. You can start to understand
the limitations or restrictions

of these classes and learn what you have to build yourself, and what comes for free in the short term to
help you get started. If

you are just learning programming then you have a whole set of relevant source code to study to look at
how other people have

used and built the tools. Reading source code is one of the easiest ways for a novice programmer to
advance their programming

skills.

14.3 How to find line numbers in Eclipse?


To help you find the line number you can:

• switch on line numbering by right clicking on the left margin of the code window (where you set
breakpoints) and select "Show line numbers"

88
15. Sample Programs in RC for:

15.1 Text box

To type a word in text box or text area we have to use the below command.

Syntax:

Sets the value of an input field, as though you typed it in. Can also be used to set the value of
combo boxes, check boxes, etc. In these cases, value should be the value of the option selected,
not the visible text.
Parameters:
locator an element locator
value the value to type
Usage:

Selenium.type(“locator”, “value”);

Selenium.type(“id=123”, “selenium”);

For sample script, please go through the script TextBox.java

15.2 Link
To click a link on web page please use the below command.

Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), call
waitForPageToLoad.

Parameters:
locator an element locator

Usage:

Selenium.click(“locator”);

Selenium.click(“id=123”);

For sample script, please go through the script Link.java

89
15.3 Button
To click a Button on web page please use the below command.

Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), call
waitForPageToLoad.

Parameters:
locator an element locator

Usage:

Selenium.click(“locator”);

Selenium.click(“id=123”);

For sample script, please go through the script Button.java

15.4 Checkbox
To check a Check box on web page please use the below command.

Check a toggle-button (checkbox/radio)

Parameters:
locator an element locator

Usage:

Selenium.click(“locator”); or Selenium.check(“locator”);

Selenium.click(“id=123”); or Selenium.check(“id=123”);

For sample script, please go through the script Checkbox.java

15.5 Radio Button

To Select a radio button on web page please use the below command.
90
Check a toggle-button (checkbox/radio)

Parameters:
locator an element locator

Usage:

Selenium.click(“locator”); or Selenium.check(“locator”);

Selenium.click(“id=123”); or Selenium.check(“id=123”);

For sample script, please go through the script radiobutton.java

15.6 Drop Down Box

15.6.1 Select value

To select a value from Dropdown we need to use the below command.

Select an option from a drop-down using an option locator.

Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for
asserting that the selected option satisfies a specification). There are several forms of Select Option Locator.

 label=labelPattern: matches options based on their labels, i.e. the visible text. (This is the default.)
o label=regexp:^[Oo]ther

Usage:

selenium.select(selectLocator, optionLocator);

selenium.select(“id=abc”,”label=shopping”);

For sample script, please go through the script Dropdown.java

91
15.6.2 Display all values

In order to display all values of DD, you need to store them in an array.

Gets all option labels in the specified select drop-down.

Parameters:
selectLocator an element locator identifying a drop-down menu
Returns:
an array of all option labels in the specified select drop-down

Usage:

selenium.getSelectOptions(selectLocator);

Store those values in an array.

String a[]=selenium.getSelectOptions(“name=sel”)

For sample script, please go through the script Dropdown1.java

15.6.3 Select values step by step

If you want to select values from dropdown step by step you have to use for loop

String b[]=selenium.getSelectOptions(selectLocator);

for (int i = 0; i < b.length; i++)


{
System.out.println(b[i]);
}

For sample script, please go through the script Dropdown2.java

15.6.4 Write all values into NotePad/Excel/Wordpad.

To write results to Notepad you have to use some Java code.

For sample script, please go through the script Dropdown3.java

92
15.7 Capture screen shot (positive)
To capture the screenshot we have to sue below command

Captures a PNG screenshot to the specified file.

Parameters:
filename the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"

Usage:

selenium.captureScreenshot(filename);

selenium.captureScreenshot("c:\\nag.png");

selenium.captureEntirePageScreenshot(filename, kwargs);
Saves the entire contents of the current window canvas to a PNG file. Parameters:
filename the path to the file to persist the screenshot as. No filename extension will be appended by
default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by
native code.
kwargs a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD"
. Currently valid options:

background
the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-
than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension
to fail and a black background is exposed (possibly obscuring black text).

15.8 Capture screen shot(with failure)


Capture screen shot(with failure)
public Scroll()
{
setCaptureScreenShotOnFailure(true);
}

93
15.9 Page scroll down using Java script

How to use Java script in selenium:


selenium.getEval(javascript);

Gets the result of evaluating the specified JavaScript snippet. The snippet may have multiple lines, but only the result
of the last line will be returned.

Parameters:
script the JavaScript snippet to run
Returns:
the results of evaluating the snippet

Page scroll down using Java script:


selenium.getEval("window.scrollBy(0,500)");

Scrolls down the page 500 pixles.

15.10 Handle alerts

Alerts
Normal alerts
selenium.getAlert();

Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.

Returns:
The message of the most recent JavaScript alert

On load alerts: This can be handled by using Selenium 2

15.11 How to read values from excel sheet

To read data from Excel sheet we need to use some java code..

FileInputStream
94
Workbook

Sheet

15.12 Create a Junit suite

Most testing frameworks have the concept of grouping a set of text fixtures into a ’suite’ so that you can
execute a number of related tests together.

Creating test suites with Selenium doesn’t appear to be obvious at first. Here’s a simple guide on how to
create and execute suites of functional tests:

Here i am using Junit scripts and Test suite()


First create two scripts....Ex:Google1 and Google2 Junit test cases

Here is the test suite....TestSuite1.java


------------------------------------------------------------
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
public class TestSuite1 extends TestCase {

public static Test suite()


{
TestSuite nag = new TestSuite();
nag.addTestSuite( Google1.class);
nag.addTestSuite( Google2.class);
return nag;
}
public static void main(String arg[])
{
TestRunner.run(suite());
}
}
------------------------------------------------------------
Run the TestSuite1.java script ...it will automatically run the Google1 and Google2....
Even though first test case is failed it will run the second one....we can change the order of the test
cases...

95
15.13 Reports

After running test scripts in eclipse it would be good if we generate reports. Junit is one the most
popular unit testing framework around.
Below are the steps to generate reports:
1. Right click on project and click on "Export" option

2. Expand "General" node and select "Ant Buildfiles", click on "Next" button
3. Select the project (let all default options),
Junit output Directory ... F:\Automation\First\junit
click on "Finish" button
build.xml file should be created under project folder

2. Now we need to add junit jar and Tools.jar file in Ant's "Global Entires"

3. Select "Window" menu, click on "Preferences"

4. In "Preferences" window, expand "Ant" root node, click on "Runtime


96
5.
6. Click on "Classpath" tab, expand "Global Entires"
7. Click on "Add External JARs" button
11. Navigate to your "eclipse" directory (where eclipse is installed). Select "plugins -
>org.junit_3.8.2.v3_8_2_v20100427-1100" directory. Select junit.jar file. and add Tools.jar which is
located under java/JDK/Lib
12. Now right click on build.xml file and select Run As -> Ant Build..

13.
14. In "Edit Configuration and launch" window, select "build", "tootltip (the script we want
to run)" and "junitreprot" checkboxes and click on "Run" button

15.
16. All your test scripts will run and finally report will be generated under the same project
directory under "junit" folder. To view JUint folder please refresh

17.
18. Click on "index.html", you will see the report

19.

97
15.14 Tool tip
Selenium.getAttaribute(“locator@foo”);

15.15 Handling Multiple windows and popups


Handling Multiple windows and popups
Extracting window IDs with Selenium :
selenium.getAllWindowIds();

Returns the IDs of all windows that the browser knows about.

Returns:
the IDs of all windows that the browser knows about.

selenium.getAllWindowNames();

Returns the Namess of all windows that the browser knows about.

Returns:
the NAMESs of all windows that the browser knows about.

selenium.getAllWindowTitles();

Returns the Titles of all windows that the browser knows about.

Returns:
the Titles of all windows that the browser knows about.

15.16 Handling HTTPS sites

We face some of the below issues while automating HTTPS sites..

HTTPS sites will show some security notifications below are some:

Firefox:

98
IE:

To avoid these type of problems we need use some commands..

To over come this issue we need to add certification

1. Need to add remote control configuration

RemoteControlConfiguration rcc = new RemoteControlConfiguration ();

2. Set TrustAllSSLCertificates flag to TRUE

rcc.setTrustAllSSLCertificates(true);

3. Pass the rcc Instance to Selenium Server

SeleniumServer server = new SeleniumServer(rcc);

99
If the above steps also doesnt work you need to install cyber villian certificate to automate HTTPS sites
(Especially for IE)

1. Extract selenium-server.jar

2. In selenium server folder Open sslSupport folder

3. It contains cybervillainsCA.cer please install that certificate

Now we can run HTTPS site without any certification errors.

100
16. Selenium RC using TestNG

16.1 How to Install TestNG plugin in Eclipse


TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it
more powerful and easier to use.

Go to tolls install new software

Install window will be opened.Click ADD button.

In Add repository window –Enter names as TestNG and URL http://beust.com/eclipse

Click OK.

Select TEstNG and click Next. And again click Next next..after installing testing just restart Eclipse to
reflect the changes.

16.2 TestNG sample script

package one;

import org.openqa.selenium.server.SeleniumServer;

import org.testng.annotations.Test;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.AfterClass;

import com.thoughtworks.selenium.DefaultSelenium;

import com.thoughtworks.selenium.Selenium;

public class FirstTNG {

101
public SeleniumServer ss;//Create a variable

public Selenium selenium;//Create a variable

@BeforeClass

public void beforeClass() throws Exception

ss=new SeleniumServer();//Create an object

ss.start();//start selenium server

selenium=new DefaultSelenium("localhost", 4444, "*firefox", "http://"); //Pass arguments to


selenium

selenium.start();//srat selenium server

@Test

public void testFirstTNG() throws Exception

//open google page

selenium.open("http://www.google.com");

//maximize window

selenium.windowMaximize();

Thread.sleep(5000);

@AfterClass

public void afterClass()

{
102
//stop selenium

selenium.stop();

//stop selenium server

ss.stop();

16.3 Reports generation using TestNG

Generating reports is easy in TEstNG compared to other frame works. TestNG will generate reports
automatically. After running the script just refresh the project.

Right click on Project and click Refresh…then u can see a new folder test-output..expand that folder you
can see INDEX.html and emailable-report.html.

These two files are the reports.

16.4 Creating Test suites using TestNG


TESTNG we need to create a test suite using XML file. For sample XML file we can use the (index.html)
report created automatically.

1. Click on Index.html
2. Click on LINK under testing.xml column.
3. Copy the XML code.
4. Now create a XML file (Right click on Project---New ---- File)
5. Give file name as testing.xml and copy the code in that file
6. Save the file.
7. Under Classes tag.add classes…and save it..
8. Right click on the XML file from Package Explorer and runas-testngsuite..
9. The scripts will run one after that another and report is created automatically.

103
17. Introduction to Web driver (Selenium 2.0)

17.1 Introduction

Selenium web driver is also known as selenium 2.0. Web driver is a tool for automating web
applications. The main aim of web driver is to provide user friendly API.

17.2 Advantages over Selenium RC(1.0)

1. Selenium 2.0 has many new exciting features and improvements over Selenium 1.
2. Selenium 2.0 has more API than selenium 1.0
3. The new Feature is integration of Web driver API.
4. By this web driver API we can overcome issues in Selenium 1.0
5. The goal is to develop an object-oriented API.
6. It is more faster than Selenium RC / 1.0
7. There are more ways to identify objects ()
8. No need of starting server.
9. Page synchronization is handled automatically.
10.

17.3 How to setup Web driver using eclipse and Junit / TestNG

The set up of Web driver is quite similar to Selenium RC.

Prerequisites:

Jdk 1.5 or above

Eclipse 3.5 or above

Jar files: All files in selenium-java-2.X.0 folder and selenium-server-standalone-2.x.0 server file.

104
1. Open Eclipse.
2. File new—Java project.
3. Enter Project Name Web Driver and click Finish.
4. A project is created.
5. Right click on JRE sys library and click buildpath—configure build path.
6. Add all external jar files (selenium-java-2.X.0 and selenium-server-standalone-2.x.0).
7. Done you are ready to write scripts using selenium webdriver.

17.4 More Ways to identify Elements

By ID:

driver.findElement(By.id(“123”));

By Name:

driver.findElement(By.name(“username”));

By Link Text:

driver.findElement(By.linkText(“Sign In and Register”));

By Partial Link Text:

driver.findElement(By.partialLinkText(“Sign In”));

By CSS:

driver.findElement(By.cssSelector(“.bUserBar.LikeRealBtn”));

By XPATH:

driver.findElement(By.xpath(”//input[@class=’Page_eRadioButton’]”));

By Class Name:

driver.findElement(By.className(”Page_eRadioButton”));

By Tag Name:

driver.findElement(By.tagName(”option”));

105
17.5 Sample scripts

Here is the sample web driver script created using Junit.

package practice; //package name

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class First {


private WebDriver driver; //Declaring variable

@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();//Creating firefox driver
driver.manage().timeouts().implicitlyWait(30,
TimeUnit.SECONDS);//implicit time out, it is like wait for page to load in
selenium rc
}

@Test
public void testFirst() throws Exception {
//open google page in maximized mode
driver.get("http://www.google.com");
//click options button
driver.findElement(By.id("gbi5")).click();
//click advanced search link
driver.findElement(By.id("gmlas")).click();
//type search word in text box
driver.findElement(By.name("as_q")).sendKeys("test");

//select value from Dropdown


new Select(driver.findElement(By.name("tbs"))).selectByVisibleText("show only
basic results");
//Click advanced search button
driver.findElement(By.cssSelector("input[type=\"submit\"]")).click();
Thread.sleep(5000);
}

@After
public void tearDown() throws Exception {
//Quit the driver
driver.quit();

}
106
}

107
18. Selenium Backed Web Driver

The Java version of WebDriver provides an implementation of the Selenium-RC API. These means that
you can use the underlying WebDriver technology using the Selenium-RC API. This is primarily provided
for backwards compatablity. It allows those who have existing test suites using the Selenium-RC API to
use WebDriver under the covers. It’s provided to help ease the migration path to Selenium-Web driver.

Sample Backed web driver script looks like this:

=================================================================

package webone;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebDriverBackedSelenium;

import org.openqa.selenium.firefox.FirefoxDriver;

import com.thoughtworks.selenium.SeleneseTestCase;

108
import com.thoughtworks.selenium.Selenium;

@SuppressWarnings("deprecation")

public class BackedSelenium extends SeleneseTestCase {

//web driver --here we are declaring the browser

WebDriver driver = new FirefoxDriver();

@Before

public void setUp() throws Exception {

String baseUrl = "http://www.google.co.in/";

selenium = new WebDriverBackedSelenium(driver, baseUrl);

@Test

public void testBackedSelenium() throws Exception {

//This is using selenium

selenium.open("/");

selenium.click("id=gbi5");

selenium.click("id=gmlas");

selenium.waitForPageToLoad("30000");

selenium.type("name=as_q", "test");

//Here we are using Webdriver

driver.findElement(By.id("as_oq1")).sendKeys("naga");

109
driver.findElement(By.id("as_oq2")).sendKeys("Webdriver");

Thread.sleep(5000);

@After

public void tearDown() throws Exception {

selenium.stop();

=====================================================

By using the above format you can use both the Selenium API and Web driver API...

110
19. Run Web Driver Scripts in Chrome

This explains you how to run your webdriver script in google chrome..

Firefox Browser:

driver=new FirefoxDriver(); --it will work and will launch your firefox browser,

Google Chrome:

driver= new Chromedriver() --- it will throw an error.

Error:

FAILED CONFIGURATION: @BeforeClass beforeClass

java.lang.IllegalStateException: The path to the driver executable must be set by the


webdriver.chrome.driver system property; for more information, see
http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from
http://code.google.com/p/chromedriver/downloads/list

To overcome this we need to download the chrome driver.exe and we have to specify the apth of
chrome driver in the script

Download path:

http://code.google.com/p/chromedriver/downloads/list

take the latest exe file. see the below image


111
save the chrome driver in a folder and you need to specify the path of driver in your webdriver script.

Below is the Sample code:

package testng;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.Test;

public class ChromedriverTest {

112
public WebDriver driver;

@BeforeClass

public void beforeClass() {

// Create chrome driver instance...

System.setProperty("webdriver.chrome.driver", "C:\\xxx\\Jar\\chromedriver.exe");

driver=new ChromeDriver();

@Test

public void testChromedriverTest() throws Exception {

driver.navigate().to("http://bing.com");

Thread.sleep(5000);

@AfterClass

public void afterClass() {

driver.quit();

Use the above code your script will run in Google chrome.

113
20. Important Web Driver Commands

Browser initiation:

WebDriver driver=new FirefoxDriver();

WebDriver driver=new SafariDriver();

WebDriver driver=new chromeDriver();

WebDriver driver=new InternetExplorerDriver();

Open URL:

driver.get("http://www.google.com");

Click a link,Check box,Radio button, button:

driver.findElement(By.id("gbqfq")).click();

Clear the text field:

driver.findElement(By.id("abc")).clear();

Type in Text box or Text Area:

driver.findElement(By.name ("username")).sendKeys("test");

Select a Value from Dropdown:

Select select = new Select(driver.findElement(By.tagName("select")));

select.selectByVisibleText("Apple");

Switch to window:

driver.switchTo().window("windowName");

Switch to Frame:

driver.switchTo().frame("frameName");

114
Switch to Alert:

driver.switchTo().alert().accept();

Confirmation Box:

driver.switchTo().alert().accept();

driver.switchTo().alert().dismiss();

Navigate Forward:

driver.navigate().forward();

Navigate Backward:

driver.navigate().back();

Using Actions Class

Drag and Drop

WebElement source = driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(source, target).perform();

Mouse Hover:

Actions builder = new Actions(driver);

WebElementtagElement =

driver.findElement(By.id("someid"));

builder.moveToElement(tagElement).build().perform();

115
21. Grid Using Web Driver

Below are the steps to run your scripts in parallel.

We can run two tests in two different browsers.

So this is used for to reduce the time.

here Test1 will run in FF and Test2 will run in IE

We can run same test in two browsers[same test or different test]. So this is used for cross browser
testing.

here test1 will run in IE and FF

Below are the commands to start server and other ports:

This is to start the HUB

116
java -jar selenium-server-standalone-2.24.1.jar -role hub

Start server on different port(5555):

java -jar selenium-server-standalone-2.24.1.jar -role webdriver -hub


http://localhost:4444/grid/register

Start server on different port(5556):

java -jar selenium-server-standalone-2.24.1.jar -role webdriver -hub


http://localhost:4444/grid/register -port 5556

To View the console below is the command:

http://localhost:4444/grid/console

Sample Script:

Test1:
package grid;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Test1 {

public WebDriver driver;


@Parameters({"browser"})
@BeforeClass
public void setUp(String browser) throws MalformedURLException {

DesiredCapabilities capabilities=null;

if(browser.equalsIgnoreCase("firefox"))
{
capabilities=DesiredCapabilities.firefox();
capabilities.setPlatform(Platform.ANY);

}
if(browser.equalsIgnoreCase("internetExplorer"))
{

117
capabilities = DesiredCapabilities.internetExplorer();
capabilities.setPlatform(Platform.ANY);

}
System.out.println("Firefox");
driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"),capabilities);

}
@Test
public void method1() throws Exception
{
driver.get("http://google.com");
Thread.sleep(15000);
}

@AfterClass
public void tearDown() {
driver.quit();
}

Test2:

package grid;

import java.net.MalformedURLException;

import java.net.URL;

import org.openqa.selenium.Platform;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeClass;

118
import org.testng.annotations.Parameters;

import org.testng.annotations.Test;

public class Test2 {

public WebDriver driver;

@Parameters({"browser"})

@BeforeClass

public void setUp(String browser) throws MalformedURLException {

DesiredCapabilities capabilities=null;

if(browser.equalsIgnoreCase("firefox"))

capabilities=DesiredCapabilities.firefox();

capabilities.setPlatform(Platform.ANY);

if(browser.equalsIgnoreCase("internetExplorer"))

capabilities = DesiredCapabilities.internetExplorer();

capabilities.setPlatform(Platform.ANY);

119
}

System.out.println("Internet explorer");

driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),capabilities);

@Test

public void method2() throws Exception

driver.get("http://www.yahoo.com");

Thread.sleep(15000);

@AfterClass

public void tearDown() {

driver.quit();

120
Below is the Test Suite

Testng1.xml:

<!-- IF you run this test two browsers will open and
two tests will run in two different browsers.
SO this is used for to reduce the time.
here Test1 will run in FF and Test2 will run in IE-->

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">


<suite name="Suite" parallel="tests" thread-count="10">

<test name="Test" preserve-order="false">


<parameter name="browser" value="firefox"></parameter>
<classes>
<class name="grid.Test1"/>

</classes>

</test>
<test name="Test1" preserve-order="false">
<parameter name="browser" value="internetExplorer"></parameter>
<classes>
<class name="grid.Test2"/>
</classes>

</test>

</suite>

121
Testng2.xml

<!-- IF you run this test two browsers will open and
same test will run in two different browsers.
SO this is used for cross browser testing.
here test1 will run in IE and FF-->

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">


<suite name="Suite" parallel="tests" thread-count="10">

<test name="Test" preserve-order="false">


<parameter name="browser" value="firefox"></parameter>
<classes>
<class name="grid.Test1"/>
</classes>

</test>
<test name="Test1" preserve-order="false">
<parameter name="browser" value="internetExplorer"></parameter>
<classes>
<class name="grid.Test1"/>
</classes>

</test>

</suite>

122

You might also like