Selenium Final
Selenium Final
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
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.
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.
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.
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.
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
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
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.
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.
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.
14
TEST CASE 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:
17
4. LOCATORS
Firebug
IE DebugBar
Google Chrome Developer Tools
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.
18
Click on Install Firebug
Click on firebug-1.6.2.xpi
Click Allow
19
Click on Install Now
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
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
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.
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
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:
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
checkbox
radio button
link
dropdown
text field
text area
button
Input
button
form
span
ol
ul
a
name
id
href
title
value
class
Type id=search
29
5.2 Finding elements by name
Type name=q
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.
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:
<input>
Syntax:
//--parent element
/child element
//element[@attribute='attribute name']
Example 1:
//button[@id='123']
31
Example 2:
<span id=456>
//span[@id-'456']/input[2]
u129747_3
u131602_3
Rightstart:
<a
href="http://www.rightstart.com/search/result/?link_location=default.leftnav&
ocat=707" class="current">Travel Gear</a>
Using attribute:
//a[@href='http://www.rightstart.com/search/result/?link_location=default.leftnav&ocat=707']
//dd[@class='last odd']/ol/li[3]/a
<a href="http://www.rightstart.com/search/result/?link_location=default.leftnav&ocat=707"
class="current">Travel Gear</a>
//a[@href='http://www.rightstart.com/search/result/?link_location=default.leftnav
&ocat=707']
32
Xpath using position:
//element[@att='attname']/element1/element2
//dd[@class='last odd']/ol/li[10]/a
Dynamic element:
//element[@att='attname']
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.
Contains
Starts-with
Syntax :
//element[text()='inner text'].
//a[starts-with(text(),'Boost')]
//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:
Syntax:
//element[contains(text(),’inner text’)]
34
For the above example the command is :
Starts with:
Syntax:
If we know the starting of the text then we have to use this command.
//a[starts-with(text(),'Boost')]
locators are a way to tell selenium which specific element we want it to act on
Why CSS
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
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:-
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
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”.
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 -->.
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.
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.
47
6.4 Analyzing the Results
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:
50
6.7 Synchronisation commands
waitForPageToLoad(timeout)
Arguments:
You can use this command instead of the "AndWait" suffixes, "clickAndWait",
"selectAndWait", "typeAndWait" etc. (which are only available in the JS API).
Pause:
pause(waitTime)
Arguments:
Difference
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.
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.
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.
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.
5. Click on Add
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.
Questions
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()
6.14 Refresh
Syntax:
refresh()
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
6.16 MouseOver
Mouse Over:
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
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:
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
}
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.
package com.devmanuals2;
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.
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);
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
59
System.out.println(aByte);
System.out.println(aNumber);
EXTENDS:
A class declaration can use the extend keyword on another class, like this:
class C extends B { … } .
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
}
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.
ARRAYS:
61
An array of ten elements
62
8. Selenium Remote Control
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.
Selenium RC components:
Selenium Server
Client libraries
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
• 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
65
Stop: (Browser)
http://localhost:4444/selenium-
server/driver/?cmd=shutDownSeleniumServer
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
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:
Example:
67
Below is the screenshot of TEST RUNNER
RESULTS:
68
9. Programming your Tests
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
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
host Specifies the IP address of the computer where the server is located. Usually,
this is the same
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.2 Procedure
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.
1. File—New—Java Project
3. Click Configure JREs in that screen. You will get a new window.
73
New Java Project with all jar files.
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.
Click Ok.
74
You can see the Referenced Libraries…
Everything is done.
Now you can write your scripts and Enjoy Selenium Automation….
Give Name First and click the check box public static void main (String []
args) click Finish
76
11. Selenium Commands
Example: - (“link=click”)
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.
link=textPattern
Select the link (anchor) element which contains text matching the specified
pattern.
77
11.2 Important Selenium Commands
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.
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestCase;
import com.thoughtworks.selenium.Selenium;
@Before
public void setUp() throws Exception { //Set UP method to start selenium and
selenium server
DefaultSelenium selenium=new
DefaultSelenium("localhost",4444,"*iehta","http://");
localhost—serverHost
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();
}
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));
}
81
@Before
public void runBeforeEveryTest() {
simpleMath = new SimpleMath();
}
@After
public void runAfterEveryTest() {
simpleMath = null;
}
@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:
Parameters:
locator an element locator
value the value to type
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
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)
selenium.getSelectOptions(selectLocator)
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)
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).
84
}
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
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
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.
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.
• 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:
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”);
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”);
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”);
15.4 Checkbox
To check a Check box on web page please use the below command.
Parameters:
locator an element locator
Usage:
Selenium.click(“locator”); or Selenium.check(“locator”);
Selenium.click(“id=123”); or Selenium.check(“id=123”);
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”);
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”);
91
15.6.2 Display all values
In order to display all values of DD, you need to store them in an array.
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);
String a[]=selenium.getSelectOptions(“name=sel”)
If you want to select values from dropdown step by step you have to use for loop
String b[]=selenium.getSelectOptions(selectLocator);
92
15.7 Capture screen shot (positive)
To capture the screenshot we have to sue below command
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).
93
15.9 Page scroll down using Java script
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
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
To read data from Excel sheet we need to use some java code..
FileInputStream
94
Workbook
Sheet
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:
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"
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”);
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.
HTTPS sites will show some security notifications below are some:
Firefox:
98
IE:
rcc.setTrustAllSSLCertificates(true);
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
100
16. Selenium RC using TestNG
Click OK.
Select TEstNG and click Next. And again click Next next..after installing testing just restart Eclipse to
reflect the changes.
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;
101
public SeleniumServer ss;//Create a variable
@BeforeClass
@Test
selenium.open("http://www.google.com");
//maximize window
selenium.windowMaximize();
Thread.sleep(5000);
@AfterClass
{
102
//stop selenium
selenium.stop();
ss.stop();
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.
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.
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
Prerequisites:
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.
By ID:
driver.findElement(By.id(“123”));
By Name:
driver.findElement(By.name(“username”));
By 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
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;
@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");
@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.
=================================================================
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")
@Before
@Test
selenium.open("/");
selenium.click("id=gbi5");
selenium.click("id=gmlas");
selenium.waitForPageToLoad("30000");
selenium.type("name=as_q", "test");
driver.findElement(By.id("as_oq1")).sendKeys("naga");
109
driver.findElement(By.id("as_oq2")).sendKeys("Webdriver");
Thread.sleep(5000);
@After
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:
Error:
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
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;
112
public WebDriver driver;
@BeforeClass
System.setProperty("webdriver.chrome.driver", "C:\\xxx\\Jar\\chromedriver.exe");
driver=new ChromeDriver();
@Test
driver.navigate().to("http://bing.com");
Thread.sleep(5000);
@AfterClass
driver.quit();
Use the above code your script will run in Google chrome.
113
20. Important Web Driver Commands
Browser initiation:
Open URL:
driver.get("http://www.google.com");
driver.findElement(By.id("gbqfq")).click();
driver.findElement(By.id("abc")).clear();
driver.findElement(By.name ("username")).sendKeys("test");
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();
Mouse Hover:
WebElementtagElement =
driver.findElement(By.id("someid"));
builder.moveToElement(tagElement).build().perform();
115
21. Grid Using Web Driver
We can run same test in two browsers[same test or different test]. So this is used for cross browser
testing.
116
java -jar selenium-server-standalone-2.24.1.jar -role hub
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;
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;
@Parameters({"browser"})
@BeforeClass
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");
@Test
driver.get("http://www.yahoo.com");
Thread.sleep(15000);
@AfterClass
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-->
</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-->
</test>
<test name="Test1" preserve-order="false">
<parameter name="browser" value="internetExplorer"></parameter>
<classes>
<class name="grid.Test1"/>
</classes>
</test>
</suite>
122