Selenium
is a functional/acceptance testing tool for web applications. It in in the same space as tools like
Selenium Advantages
- The core is written in javascript so it runs directly in a browser, just as real users do
- Supported on OS X, Linux, and Windows
- Very simple to learn and use
- Open Source (Apache License 2.0)
- Selenium Remote Control!!!
Key Components
- Selenium Core – The core of Selenium written in pure JavaScript/DHTML. This is all that is required in order to start using Selenium
- Selenium IDE (Firefox Addon) – Integrated development environment for recording and playing tests.
- Selenium RC (Remote Control) – Allows you to write automated web functional/acceptance tests in any programming language.
Selenium Core
Installation
- Download the latest release
- Place the downloaded folder (i.e. selenium-core-0.8.2) in the webroot of the webserver with the app to be tested. This is a JavaScript security requirement, ‘same origin‘ policy. (Later in this talk we’ll explain how to get around this).
Writing your First Test
Where to put the tests
The tests can really reside anywhere on the web server (just need to accessable from same domain of the app you are testing). So, just place them in the area that makes most sense for you organization wise.
For this example we will place them in the web app to be tested in a ‘tests’ folder.
What we will be testing
For this talk I have written a VERY tiny PHP application with a simple login page. We’ll use this to test some of the aspets of Selenium.

How test cases are constructed
OpenQA used a very KISS method for creating a test case. You simply take your favorite HTML editor and create an HTML table with 3 columns (). Then add a row () for each test step (called a command).
The general pattern for these command rows are 
Depending on the command, target or value can be optional or required. (more about this later).
Below is about the simplest test possible. It just useses the open command to load the browser with a value of the Login page and then uses the assertTitle command to verify that the title element (<title>) for the page has the value “Selenium Demo: login”.
Note that any table row with <> 3 columns is ignored so it can be use for commenting your tests as we do in row 1 below.
This test writing syntax is refered to as ‘HTML Selenese’
This file is saved in the tests folder of the app as TestLoginPageLoads.html
Running Your First Test
First, need a Test Suite to house the Test Case(s)
Test Cases are organized into collections using Test Suites.
Again, in the spirit of keeping things simple, a Test Suite is an HTML
file with a 1 column table. In each row of that table you put a
hyper-link pointing to the test you want to run.

This file is also saved in the tests directory with the name TestSuite.html
Now to actually run it…
Open a browser and navigate to the TestRunner file in Selenium core that you installed locally. It is located at…
{selenium-install-dir}/core/TestRunner.html
You should see something simmilar to this
In the upper left “Test Suite:” text box, type the relative path to the …/tests/TestSuite.html file created above (/selenium-talk/tests/selenium/TestSuite.html in this case) and click the Go button
The Test Suite should load in the left frame and the middle frame will list the Test Cases along with their individual steps
Click the
button to run this test.
This is a very simple test so things happen very quicly but the web app reference in the suite will load in the bottom frame and the test will interact with it there. The summary section will show the passed/failed stats for the Test Suite run and the Test Suite and Test Cases lists will colorize depending on the test outcome (green=pass / red=fail)

Some examples of tests
A Closer Look at Test Cases
Commands
There are 3 types of commands
1 Actions
example actions are click(locator), goBack(), setCursorPosition(locator,position), keyPress(locator,keySequence), dragdrop(locator,movementsString), …
Selenium Actions mimic the actions the user would take in interacting with the web app.
2 Accessors
Accessors examine the state of the applications and store the result in variables. Examples would be storeElementWidth(locator, variableName), storeBodyText(variableName), storeSelectedId(selectLocator,variableName), …
3 Assertions
For any given Accessor there are typically one or more related Assertions. Assertions, like Accessors, are able to examine the state of the application but instead of storing the value they retrieve, they verify that it meets a pre-defined expected value.
Assertions themselves com in 3 versions
- assert – If this fails, the test is aborted
- verify – If this fails, the test will log the failure, but continue
- waitFor – These wait for the tested condition to become true. They will fail and hault the test after the the value for current timeout setting expires (see the setTimeout(timeout) Action)
For example the Accessor – storeLocation(storageVariable) retrieves the absolute URL of the current page and stores it in the variable, storageVariable.
its (automatically generated) assertions are
- assertLocation ( pattern )
- assertNotLocation ( pattern )
- verifyLocation ( pattern )
- verifyNotLocation ( pattern )
- waitForLocation ( pattern )
- waitForNotLocation ( pattern )
Note: You do not need to use an Accessor prior to using one of its related Assertions. As in our example Test Case, TestLoginPageLoads, we simply used assertTitle directly after the open command (and never used storeTitle).
There are many, many Actions, Accessors, and Assertions (and you can also easily define your own) so be sure to give the Selenium reference a good read as it details them all.
Element Locators and Patterns
On the previous page for the Action, Accessor, and Assertion commands, you may have noticed the references to ‘locator‘ and/or ‘pattern‘ in the parameters for those Commands.
(Element) Locators
The Element Locator concerns the Target that a given Command uses. They tell Selenium which HTML element a Command refers to. There are quite a few techniques the Locator can use so you are sure to find one that works for you.
ElementLocators are in the form: {locator-prefix}={locator-string}
ex.
command target value
verifyText id=koan_body *mary had a little lamb*
—————
<following descriptions are from the OpenQA site>
- identifier=id: Select the element with the specified @id attribute. If no match is found, select the first element whose @name attribute is id. (This is normally the default; see below.)
- id=id: Select the element with the specified @id attribute.
- name=name: Select the first element with the specified @name attribute.
The name may optionally be followed by one or more element-filters, separated from the name by whitespace. If the filterType is not specified, value is assumed.
-
- name=flavour value=chocolate (useful for check-boxes and radio-buttons)
- dom=javascriptExpression: Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block.
- dom=document.forms['myForm'].myDropdown
- dom=document.images[56]
- dom=function foo() { return document.links[1]; }; foo();
- xpath=xpathExpression: Locate an element using an XPath expression.
- xpath=//img[@alt='The image alt text']
- xpath=//table[@id='table1']//tr[4]/td[2]
- xpath=//a[contains(@href,'#id1')]
- xpath=//a[contains(@href,'#id1')]/@class
- xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
- xpath=//input[@name='name2' and @value='yes']
- xpath=//*[text()="right"]
- link=textPattern: Select the link (anchor) element which contains text matching the specified pattern.
- css=cssSelectorSyntax: Select the element using css selectors. Please refer to CSS2 selectors, CSS3 selectors for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package.
- css=a[href="#id3"]
- css=span#firstChild + span
Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type,
nly-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).
Without an explicit locator-prefix, Selenium uses the following default strategies:
- dom, for locators starting with “document.”
- xpath, for locators starting with “//”
- identifier, otherwise
Patterns
Patterns concern the Value that a given Command is looking for.
Patterns are in the form {pattern-prefix}:{pattern}
The Pattern techniques are:
- glob:{pattern}
- globs are simple pattern matchers. ‘*‘ matches any sequence of characters and ‘?‘ matches any single character.
- regex:{regular-expression}
- The pattern matcher we know and love. See your javascript engine for the specifics of the regex engine in use.
- exact:{literal-sting}
If no pattern-prefix is given then Selenium defaults to glob
Often for simple ElementLocators you can get away with id=locator-string. For more complex locators I would recoment you get aquanted with xpath. You can go here for a good xpath tutorial and Viktor Zigo has written an excellent xpath firefox plugin. For Patterns use globs for simple matches and regex when you need a bit more sophisticated match.
You can go here for a good xpath tutorial
Selenium IDE
This is implemented as a Firefox add-on. It is a graphical tool you can use to quickly record edit and debug tests.
It installs like any other FF plugin so go to OpenQA’s site and download and install. Once you restart Firefox, SeleniumIDE should be listed under the tools menu.
To use it, simple navigate to the page in the application where you want to start testing, then go to Tools -> SeleniumIDE to launch the tool.
Selenium IDE starts in record mode so you can jsut start interacting with the browser and your actions will be recorded in the IDE. A movie is worth (a bunch) of words, so see this screen cast on OpenQA’s site for a quick walk through.
So essentially to use the IDE to record a test
- After determining an interaction with the web application to test.
- Navaigate (in FF) to the first page of the interaction
- Start the Selenium IDE
- Follow the steps of the interaction
- Click the stop recored button of the IDE
- In the Selenium Menu, go to File -> Save Test and save the test into your web app’s tests directory.
- Add the saved test to the approprieate Test Suite.
note: During the test recording, you can right-click elements in the page and get a menu showing all the available Commands for the element.

Selenium Remote Control
This quote for the OpenQA site pretty much sums up the power of Selenium RC
“Selenium Remote Control is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser.”
Installing SeleniumRC
Install Using PEAR
On my first atempt to install the PHP client driver with PEAR I got this
sudo pear install Testing_Selenium
Failed to download pear/Testing_Selenium within preferred state"stable", latest release is version 0.3.0, stability "beta",
use "channel://pear.php.net/Testing_Selenium-0.3.0" to install
Cannot initialize 'Testing_Selenium', invalid or missing package file
Package "Testing_Selenium" is not valid
install failed
Selenium is still in Beta, no problem… using the suggested command worked fine. If you have any trouble here see PEAR’s docs
sudo pear install channel://pear.php.net/Testing_Selenium-0.3.0
downloading Testing_Selenium-0.3.0.tgz ...
Starting to download Testing_Selenium-0.3.0.tgz (2,414,300 bytes)
...........................................done: 2,414,300 bytes
install ok: channel://pear.php.net/Testing_Selenium-0.3.0
Then just be sure that your PEAR directory is in your PHP include path and you are good to go.
Install Manually
Just grab the package from PEAR and place the Testing_Selenium-0.3.0 directory where it will be found in the PHP include_path. Also it is noted on the OpenQA site that the PHP client will be included in future releases of the SeleniumRC download ( >= 0.9.1) so that will be a second way to manually install.
Source
If you want to view or check out the source, you can do that…
you can check ou the source for SeleniumRC at
svn co https://svn.openqa.org/svn/selenium-rc/trunk
you can view the source at
http://svn.openqa.org/fisheye/viewrep/selenium-rc/trunk
Writing the test in PHP
The Code
The Selenium Server
Selenium Server
To run your test using the PHP client (or any of the clients) you need to have the Selenium Server running in a separate process.
Selenium Server is a Java program and requires a JRE >= 1.5.0. You can check your version by typing java -version on the commandline.
$ java -versionjava version "1.5.0_07"Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_07-164)Java HotSpot(TM) Client VM (build 1.5.0_07-87, mixed mode, sharing)
If you get something like ‘java: command not found’ or your version is < href="http://java.sun.com/javase/downloads/index_jdk5.jsp">Java Runtime Environment (JRE) 5.0.
Compatible Browser
Best supported is Firefox and IE. If you have these installed in their default locations you should be good. If not place their corresponding executables in your OS’s PATH environment variable.
Starting The Server
The command to start the server is in the form java -jar {path to selenium-server.jar}. If you installed the server with PEAR, the jar file should be in your {pear install dir}/data/Testing_Selenium/
$ java -jar /usr/local/php/lib/php/data/Testing_Selenium/selenium-server.jarapplication/xhtml+xmlMar 5, 2007 8:53:50 PM org.mortbay.http.HttpServer doStartINFO: Version Jetty/0.9.0Mar 5, 2007 8:53:50 PM org.mortbay.util.Container startINFO: Started HttpContext[/,/]Mar 5, 2007 8:53:50 PM org.mortbay.util.Container startINFO: Started HttpContext[/selenium-server,/selenium-server]Mar 5, 2007 8:53:50 PM org.mortbay.util.Container startINFO: Started HttpContext[/selenium-server/driver,/selenium-server/driver]Mar 5, 2007 8:53:50 PM org.mortbay.http.SocketListener startINFO: Started SocketListener on 0.0.0.0:4444Mar 5, 2007 8:53:50 PM org.mortbay.util.Container start
INFO: Started org.mortbay.jetty.Server@6672d6
Just leave this server running during your tests. There is no need to stop/start it between test runs.
Running Your First PHP Test
In a terminal window other than the on the server is running in. Navigate to the directory in the web app holding the test written in PHP.
When you run the PHP file…
$ php test-login.php
In the Selenium Server window you should see something like…
Got result: OK,Selenium Demo App: login on session 218697GET: cmd=testComplete&sessionId=218697Killing Firefox...Got result: OK on session 218697
Then you should see the output of the PHP file.
Title Equal: 'Selenium Demo App: login'
know bug on OS X : launching FireFox
Using SeleniumRC with xUnit Frameworks
Stitching SeleniumRC into your Testing Framework
In order to make SeleniumRC more maintainable and scalable you can leverage your language’s xUnit framework (PHPUnit) in this case.
Example PHPUint/SeleniumRC Test (from the OpenQA) site. Notice that we are overcoming the Javascript’s “Same Origin Policy“.
public function tearDown()
{
$this->selenium->stop();
}
public function testGoogle()
{
$this->selenium->open(“/”);
$this->selenium->type(“q”, “hello world”);
$this->selenium->click(“btnG”);
$this->selenium->waitForPageToLoad(10000);
$this->assertRegExp(“/Google Search/”, $this->selenium->getTitle());
}
With this setup, you SeleniumRC tests can easily be incorperated into an existing Unit Testing framework. The SeleniumRC test benefit from all the ease of use and scalability of the xUnit frameworks.
One more note, to get a headstart on building SeleniumRC tests you can use the export option of SeleniumIDE

Selenium: Further Reading, Examples