Selenium WebDriver
Selenium WebDriver
Software Quality
Assurance
Telerik Software Academy
http://academy.telerik.com
The Lector
Anton Angelov
QA Architect
Licensing Team
@angelovstanton
Site: http://automatetheplanet.com
2
Table of Contents
Selenium WebDriver
Element Locators
Custom Format
Page Object Model
Selenium Grid
3
Brief History of The
Selenium
Selenium RC vs.
WebDriver
Selenium-RC "injected" JS functions
into the browser when the browser
was loaded and then used its JS to
drive the AUT within the browser
6
Selenium WebDriver
Why Use the
WebDriver?
Selenium WebDriver
A tool for automating web
application testing
Developed to better support
dynamic web pages where elements
of a page may change without the
page itself being reloaded(AJAX)
Makes direct calls to the browser
using each browser’s native
support for automation the page
itself being reloaded. 8
Binding WebDriver Drivers
Code Wire (IE, Firefox,
(C#, Java …) Protocol Chrome …)
Selenium 1.0 +
WebDriver =
Selenium 2.0
The WebDriver Wire
Protocol
All implementations of WebDriver
that communicate with the
browser, or a Remote WebDriver
server shall use a common wire
protocol
The wire protocol defines a RESTful
web service using JSON over HTTP
implemented in request/response
pairs of "commands" and
"responses“
Full Documentation: 10
JSON Selenium REST
API
POST Request
URL: http://
localhost:64649/session
{ BODY:
"desiredCapabilities": {
"browserName": "chrome",
"chrome.switches": [ ],
"chromeOptions": {
"args": [ ],
"extensions": [ ]
},
"javascriptEnabled":
true,
"platform": "WINDOWS",
"version": ""
}
}
Rest Console Demo
Setting Up WebDriver
Using NuGet packages
13
Creating Driver
Create an instance of a driver
Note: additional steps are required
to use Chrome Driver, Opera Driver,
Android Driver and iPhone Driver
IWebDriver driverOne = new FirefoxDriver();
IWebDriver driverTwo = new InternetExlorerDriver();
Navigate to page
driver.Url = "http://www.google.com";
14
Getting Started
Choose and download browser
driver you want to use for your
tests (ex. Chrome) The IWebDriver
interface can be find
using OpenQA.Selenium; under
using OpenQA.Selenium.Chrome; OpenQA.Selenium
namespace
namespace WebDriverDemo
{ You have to tell the
class Program WebDriver API where
{ this
static void Main(string[] args)
{
ChromeDriverServer is
located
IWebDriver driver = new ChromeDriver(@"C:\
libraries");
driver.Url= "http://www.google.com";
}
}
}
15
Element Locators
Locating Elements
Elements can be located by the same
properties as in the IDE
By ID
IWebElement element =
driver.FindElement(By.Id("coolestWidgetEvah"));
By Class
IList<IWebElement> cheeses =
driver.FindElements(By.ClassName("cheese"));
By Tag Name
IWebElement frame =
driver.FindElement(By.TagName("iframe"));
17
Locating Elements(2)
By Name
IWebElement cheese =
driver.FindElement(By.Name("cheese"));
By Link Text
IWebElement cheese =
driver.FindElement(By.LinkText("cheese"));
By XPath
IList<IWebElement> inputs =
driver.FindElements(By.XPath("//input"));
By CSS Selector
IWebElement cheese =
driver.FindElement(By.CssSelector("#food
span.dairy.aged"));
18
Locating Elements(3)
Chain of locators
IWebElement cheese = this.driver.
FindElement(By.ClassName(“firstElementTable")).
FindElement(By.Id(“secondElement"));
XPath Support
Try to use native XPath support of browsers.
On those that don’t have, WebDriver
provided
Driver
its own implementation
Tag and Native XPath Support
Attribute
Documentation: http
XPath Axes
Location Path Expression
axisname::nodetest[predicate]
//td[@id=‘elementId’]/following-sibling::td[1]
AxisName Expression
ancestor Selects all ancestors (parent,
grandparent, etc.)
descendant Selects all descendants (children,
grandchildren, etc.)
following-sibling Selects all siblings after the current
node
preceding-sibling Selects all siblings before the current
node
child Selects all children of the current node
parent Selects the parent of the current node
attribute Selects all attributes of the current
Documentation: node
XPath Locators Demo
IWebElement Members
25
Wait Steps
Explicit wait
WebDriverWait wait =
new WebDriverWait(driver,
TimeSpan.FromSeconds(10));
IWebElement myDynamicElement =
wait.Until<IWebElement>(
(d) =>
{ return
d.FindElement(By.Id("someDynamicElement")); }
Implicit wait
);
driver.Manage().Timeouts().
ImplicitlyWait(TimeSpan.FromSeconds(10));
26
Implicit vs Explicit Wait
Implicit Wait – assert action
executed in exact interval
(Performance Testing)
Explicit Wait – use it for dynamic
pages where you don’t cate about
the execution time (Functional
Testing)
Thread.Sleep() – don’t use it!
Type Text
Type Text into a field using Selenium
WebDriver SendKeys() function
IWebElement element =
driver.FindElement(By.Name("search"));
element.SendKeys("telerik");
28
Select DropDown Value
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option
value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
30
Verify Text Steps
WebDriver does not support the well-
known commands of Selenium IDE
like verifyTextPresent
We can implement so
31
Asserts
There wasn’t any built-in method to
assert text on a page
You can do something along the lines
of
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver(@"C:\
libraries");
driver.Url= "http://www.google.com";
Assert.AreEqual("Google", driver.Title);
}
32
Reporting Results
The test results are limited by the
Unit Testing Framework we use
ex. NUnit, MSTest, Gallio
33
WebDriver Demo
C# Formatters
Plugins for Selenium IDE
add WebDriver backed Selenium
formatters
allows users to take advantage of
WebDriver without having to modify
their tests
https://addons.mozilla.org/en-US/firef
ox/addon/webdriver-backed-formatte
rs/
35
Custom Format
You can add any format you like by
writing JavaScript code
Open Options dialog ->"Options…"
in the menu bar -> "Formats" tab
Create a new format by clicking
"Add" button
There are 3 empty functions
parse
format
formatCommands
36
Custom Format (2)
The "parse" function is almost
opposite of "format". This function
parses the String and updates test
case
function parse(testCase, source) {
var doc = source;
var commands = [];
while (doc.length > 0) {
var line = /(.*)(\r\n|[\r\n])?/.exec(doc);
var array = line[1].split(/,/);
if (array.length >= 3) {
var command = new Command();
command.command = array[0]; command.target = array[1];
command.value = array[2]; commands.push(command);
}
doc = doc.substr(line[0].length);
}
testCase.setCommands(commands);
}
37
Custom Format (3)
The "formatCommands" function is
similar to "format" function, but is
used to copy part of the test case
into the clipboard
function formatCommands(commands) {
var result = '';
for (var i = 0; i < commands.length; i++) {
var command = commands[i];
if (command.type == 'command') {
result += command.command + ',' + command.target + ',' +
command.value + "\n";
}
} 'ext.Driver.Navigate().GoToUrl
return result; ("' +
}
command.target.toString() +
'");';
38
Custom Format (4)
The "format" function creates an
array of commands contains
command object (Command,
Target, Value)
function format(testCase, name) {
var result = '';
var commands = testCase.commands;
for (var i = 0; i < commands.length; i++) {
var command = commands[i];
if (command.type == 'command') {
result += command.command + ',' + command.target +
',' + command.value + "\n";
}
} return
return result;formatCommands(testCase.comman
} ds);
39
C# Formatters Demo
40
Refactoring for Page
Object Model
The PageFactory class is an extension
to the PageObject design Install
patternSelenium
WebDriver Support
Classes package
private IWebDriver driver;
[FindsBy(How = How.Id, Using = "SearchTerm")]
private IWebElement Search; // How.Id = SearchTerm
41
Page Object Model
Demo
Phantom JS
PhantomJS is a headless WebKit
scriptable with a JavaScript API
It has fast and native support for
various web standards:
DOM handling, CSS selector, JSON,
Canvas, and SVG
Download from
http://phantomjs.org/download.html
43
Selenium Grid
Selenium-Grid
Selenium-Grid allows you run your
tests on different machines against
different browsers in parallel
Selenium
Hub
Test
45
Selenium Server
The Selenium Server
Launches and kills browsers
Interprets and runs the Selenese
commands passed from the test
program
Acts as an HTTP proxy, intercepting
and verifying HTTP messages
passed between the browser and
the AUT
46
Selenium Server
Selenium Server
Receives Selenium commands from
the test program
Interprets them
Reports back to your program the
results of running those tests
Bundles Selenium Core and
automatically injects it into the
browser
When the test program opens the
browser 47
Download Selenium
Server
Selenium Server can be
downloaded from:
http://seleniumhq.org/download/
48
Installing Selenium
Server
The Selenium RC server is simply a
Java jar file (selenium-server.jar)
Doesn’t require any special
installation
Just download the zip file and
extract the server in the desired
directory
49
Running Selenium
Server
Running Selenium Server requires
Java Development Kit (JDK) to be
installed on your machine and
included in the class path
http://
www.oracle.com/technetwork/java/j
avase/downloads/index.html
Use CMD
Navigate to the directory where
Selenium RC’s server is located and
run the following from a command-
50
Setup Selenium-Grid
Step 1: Start the hub
java -jar selenium-server-standalone-2.14.0.jar -role
hub
Step 2: Start the nodes
java -jar selenium-server-standalone-2.14.0.jar -role
node -hub http://localhost:4444/grid/register
Using grid to run tests
DesiredCapabilities capability =
DesiredCapabilities.Firefox();
Driver = new RemoteWebDriver(new
Uri("http://localhost:4444/wd/hub"), capability);
54
Why to Automate?
1. Regression
55
Why to Automate?(2)
2. System Level Testing
57
Why to Automate?(4)
4. Exact Requirements
58
Why NOT to Automate?
(5)
59
Selenium WebDriver
?
?
?
Questions
?
?
?
?
?
? ?
Exercises
1.Create Automated Selenium WebDriver
Test for
Log in in
http://www.stage.telerikacademy.com/. Use
appropriate validations to create a good test
Go to “Settings” and fill in all the fields with
information about yourself
Save changes and verity that updated
information is shown on your profile page
Test if the validation of the input fields works
properly. Think of an appropriate way to
organize your validation tests
Think how to log test errors 61
Free Trainings @ Telerik
Academy
C# Programming @ Telerik
Academy
csharpfundamentals.telerik.com
Telerik Software Academy
academy.telerik.com
Telerik Academy @ Facebook
facebook.com/TelerikAcademy
Telerik Software Academy Forums
forums.academy.telerik.com