SlideShare a Scribd company logo
Selenium WebDriver
Training
Vijay Ramaswamy
Test Architect & Consultant
Course structure
2
Module Topics covered
Selenium User • The basics of Selenium
• Understanding script execution
Selenium Practitioner • Deep-dive into WebDriver
• Test design patterns
• Understanding basic script development
Selenium Expert • Advanced concepts
• Understanding “real-world” script development &
maintenance
Pre-requisites
 You will need to be familiar with the Java programming language and Core
Java concepts
 Familiarity with the basic concepts of version control using Subversion or Git
would be useful
3
Demo websites for sample exercises
 http://automationpractice.com
 http://newtours.demoaut.com/
 http://web2.0calc.com/
 http://demoqa.com/
 http://www.way2automation.com
4
Reference material
 The Selenium official website is the best place to start for learning about
Selenium
 Navigate to www.seleniumhq.org and click on the Documentation link
 Code samples to be referenced throughout this training:
 https://github.com/vijkris99/test-framework-basics
 Reference Automation Framework (autopia4j):
 https://github.com/autopia4j
 https://autopia4j.github.io/autopia4j-core-apidocs/index.html
 https://autopia4j.github.io/autopia4j-webdriver-apidocs/index.html
5
Selenium User Module
Vijay Ramaswamy
Test Architect & Consultant
Software you will need
 Chapter I:
 Mozilla Firefox
 Selenium IDE plugin
 Any additional browser such as Google Chrome or Microsoft Edge/IE
 Chapter II:
 Java and Eclipse (or any other IDE of your choice)
 JUnit and TestNG plugins for Eclipse
 Subversion / Git for version control
 Apache Ant / Apache Maven
7
Chapter I
(2 hours)
8
In this chapter…
 An introduction to Selenium
 The Selenium suite of tools
 The Selenium IDE
 Locating UI elements within the browser
9
An introduction to Selenium (~20 mins)
 What is Selenium?
 Selenium automates browsers
 Supports every major browser out there
 Has achieved widespread adoption and has a vibrant community
10
An introduction to Selenium (contd.)
 Why was it named so?
 Mercury is a liquid metal, which can cause great harm to humans (including death)
if exposed -> this is commonly referred to as Mercury poisoning
 Selenium is a chemical that is considered a possible antidote for Mercury poisoning
 At the time that Selenium was created, Mercury was the name of the company
which owned a popular automation tool called Quick Test Professional (QTP).
Mercury was subsequently taken over by HP.
 While QTP (now called UFT) is quite popular in the testing industry, proponents of
Selenium have criticized the tool for various reasons. Selenium was created in
direct competition to QTP, and that is how it got its name ;)
11
An introduction to Selenium (contd.)
 A brief history of Selenium:
 Selenium 1.0 born @ ThoughtWorks in 2004
 WebDriver born @ Google in 2006
 Selenium 1.0 merged with WebDriver in 2008, giving rise to Selenium 2.0
 Selenium 1.0 deprecated and eventually sunset
 What Selenium cannot do:
 Cannot send HTTP requests
 Cannot interact with embedded objects in web pages, such as videos, java applets,
flash, PDF files, etc.
12
The Selenium suite of tools (~10 mins)
 Selenium IDE:
 Integrated Development Environment
 Firefox plugin that enables basic Record & Playback
 Acts as a useful aid during script development
 The only real “tool” within the Selenium suite
 Selenium RC:
 Initial version of Selenium
 RC = Remote Control
 Provides an API to automate browsers
 Based on proxy injection of JavaScript based commands
 Currently deprecated
13
The Selenium suite of tools (contd.)
 Selenium WebDriver:
 Current version of Selenium
 Provides an API to automate browsers (completely different from the Selenium RC
API!)
 Leverages native automation support provided by individual browsers
 Selenium Grid:
 A mechanism to scale test execution by distributing it across multiple machines
14
The Selenium IDE (~30 mins)
 Installing the IDE
 Using the IDE:
 Recording a test script
 Playing back a test script
 Saving a test script
 “Selenese” commands
 Assertions and Verifications
15
Sample exercises
 Record (and save) at least 2 workflows on one of the demo websites
 Include Assert/Verify validations as relevant
 Ensure that the scripts play back successfully
 Discuss the pros and cons of Selenium IDE
16
Locating UI elements within the browser
(~60 mins)
 Selenium identifies UI elements using “locators”:
 A locator should uniquely identify the element under consideration
 Selenium supports many different kinds of locators -> apply judgement while
choosing from among these
 Test your locator before using it within a script!
 The first step to identifying the locator for a given UI element is to view the
HTML source:
 Basic method: Right click on the page in your browser -> View Source
 Recommended method: Use the development tools available within your browser!
17
Locating UI elements within the browser
(contd.)
 Locating by ID, Name:
 Most preferred locator strategy
 Can be used only when the element has a unique ID or Name attribute
 Locating by LinkText, Partial LinkText:
 Another preferred locator strategy
 Relevant only for hyperlink elements
 Locating by Tag Name, Class Name:
 Not used very frequently because these are not unique most of the time
18
Locating UI elements within the browser
(contd.)
 The next 2 locator strategies provide the most advanced capabilities:
 This directly translates into higher complexity and longer learning curve
 Use these only when all other locator strategies have been exhausted:
 It is not “cool” to use advanced locators just for the sake of using them!
 Locating by XPath:
 A query language used to select specific nodes within an XML document
 Provides extensive capabilities to traverse through an XML document as a “tree”
 Applicable to web app automation since HTML is a subset of XML
19
Locating UI elements within the browser
(contd.)
 Locating by XPath (contd.):
 XPath syntax and examples:
 Searching for a specific node within an XML/HTML document
 Absolute vs. relative XPaths
 Filtering nodes by attributes
 Filtering nodes by text
 Using regular expressions while filtering nodes
 Combining multiple filters together
20
Locating UI elements within the browser
(contd.)
 Locating by XPath (contd.):
 Best practices:
 Keep XPaths as short as possible -> the longer an XPath is, the more the chances of it
being brittle
 Avoid using indexes as far as possible -> If a developer moves around UI elements, your
XPaths stop working
 If an element is not directly identifiable by an XPath, try looking at the element’s parents
or siblings -> Chances are, one of those are unique, and you can derive an XPath from that
point
21
Locating UI elements within the browser
(contd.)
 Locating by CSS selectors:
 CSS = Cascading Style Sheets
 Used by web developers to apply UI formatting to web pages
 Formatting can be targeted at specific UI elements using selectors:
 Element selector: “All level-1 headings (<h1>) should be in blue color”
 ID selector: “All elements having ID = ‘danger’ should be highlighted in red”
 Class selector: “All elements having class = ‘centered’ should be aligned in the center of
the page”
 Selenium leverages CSS Selectors to identify UI elements to interact with
 CSS selectors reference
22
Locating UI elements within the browser
(contd.)
 In general, CSS selectors and XPath offer a similar set of capabilities, and
choosing between the two is often a matter of personal preference:
 One minor difference is that CSS selectors tend to be more compact compared to
XPaths
 All best practices mentioned under the XPath section also apply to CSS selectors
23
Sample exercises
 Become familiar with the usage of Chrome Dev tools:
 Selecting elements
 Highlighting elements
 Validating your XPath and CSS Selectors
 Navigate to one of the demo websites:
 Pick any 5 UI elements and identify each of them using at least 2 different locators
 Pick any element which does not have a unique ID/Name, and identify it using 3
different XPath expressions
 Repeat the same exercise using CSS Selectors
 Compare all the selectors used in the above exercises and call out pros and cons of
each one
24
Sample exercises (contd.)
 Open the Selenium IDE:
 Edit one of your recorded scripts and add a step using the “Select Target”
functionality
 Navigate to the relevant page and try to highlight UI elements from your script
 Examine the locators generated by the IDE and replace any brittle locators suitably
25
Chapter II
(2 hours)
26
In this chapter…
 A typical Selenium test harness:
 An introduction to testing frameworks
 An introduction to build automation tools
 An introduction to build automation servers
27
An introduction to testing frameworks
(~75 mins)
 A testing framework provides the basic infrastructure required to design and
execute automated test cases, and report on test results
 Introduction to JUnit and TestNG:
 Popular unit testing frameworks in the Java ecosystem
 Use Java annotations to manage the test lifecycle:
 JUnit: @Test, @Before, @After, @BeforeClass, @AfterClass
 TestNG: @Test, @BeforeMethod, @AfterMethod, @BeforeSuite, @AfterSuite
 Use Asserts and Matchers (such as Hamcrest or AssertJ) to validate specific test
conditions that may be required as part of your tests
28
An introduction to testing frameworks
(contd.)
 Introduction to JUnit and TestNG (contd.):
 Execute tests:
 Using Eclipse plug-ins (most common)
 Using the command line
 Using an XML file (TestNG only)
 View test results:
 Using Eclipse plug-ins (most common)
 Export results to custom formats such as XML or HTML
 Out of the box HTML results (TestNG only)
 Use Reporter.log() method to send custom messages to test report
29
An introduction to testing frameworks
(contd.)
 Introduction to JUnit and TestNG (contd.):
 In summary, a leap ahead from using a simple main() method to run your tests!
 Refer to the links on the resources slide to access some sample scripts built using
JUnit and TestNG
 Selenium does not have a built-in test runner or reporting mechanism:
 This is where JUnit/TestNG comes in
 Note that Selenium tests are not considered unit tests, although we leverage a unit
testing framework
30
Sample exercises
 Write a simple calculator program, and design white box tests for your
program using JUnit or TestNG
 Extend your scripts to use Hamcrest matchers or AssertJ
 Export one of your scripts to the JUnit or TestNG format from the Selenium
IDE
 Examine the basic structure of the exported scripts
 Become familiar with the clipboard formatting functionality within the
Selenium IDE
31
An introduction to build automation
tools (~15 mins)
 A build automation tool automates the creation of a software build, including
processes such as compiling, packaging, deploying, running automated tests,
etc.
 Oversimplified view: A glorified batch file!
 Apache Ant and Apache Maven are 2 of the most popular build automation
tools in the Java ecosystem
 Introduction to Apache Ant:
 Ant = Another Neat Tool
 Processes build scripts written using XML (typically named build.xml):
 Task = Basic commands
 Target = Collection of commands to accomplish a specific goal
 The JUnit / TestNG tasks
32
An introduction to build automation
tools (contd.)
 Introduction to Apache Ant (contd.):
 Installing Ant:
 Eclipse comes pre-installed with the Ant plugin
 If you want to run Ant from the command line, you need to install it separately:
 Ensure that the “JAVA_HOME”, “ANT_HOME” and “Path” environment variables are configured as
appropriate
 Running an Ant script:
 From the command line: Use the “ant” command
 From Eclipse: Right click on build.xml -> Run As -> Ant build
 From a build automation server such as Jenkins: Refer next slide
 Introduction to Apache Maven:
 Refer to my presentation on Maven Basics
33
An introduction to build automation
servers (~10 mins)
 A build automation server:
 Implements the build automation process on a web based server, with the aim of
centralizing the build for the entire team
 Offers a browser based UI to enable users to configure their builds as required
 Typically integrates with one or more build automation tools, and usually does not
attempt to directly automate the build process
 Provides additional capabilities such as scheduled builds, auto-triggered builds,
integration with source code repositories, etc., which makes them indispensable
towards implementing Continuous Integration and Continuous Delivery
 Some of the popular build automation servers out there include
Jenkins/Hudson, Travis CI, Bamboo, MS TFS, TeamCity, etc.
34
An introduction to build automation
servers (contd.)
 Introduction to Jenkins:
 Open source server with a vibrant community
 Fork of the Hudson project
 Vast ecosystem of plugins that enable integration with various version control
tools, build automation tools, testing tools, etc.
 Projects are managed as “jobs”, which typically consist of 3 parts:
 Build triggers
 Build steps
 Post-build actions
 Jobs can be managed in a distributed fashion across multiple machines, using a
master-slave architecture
35
An introduction to build automation
servers (contd.)
 Executing an Ant build from Jenkins:
 Ensure that Ant is setup properly on the Jenkins host machine (You should be able
to run Ant from the command line)
 Configure JDK and Ant within the Jenkins System Configuration
 Create a new job
 Point the job to your source code repository
 Add “Invoke Ant” as a build step
 Build your job!
 Sample exercise:
 Install Jenkins and try setting up a job to run your automated
scripts
36
Module recap
In this module, you learnt:
 An introduction to Selenium
 The Selenium suite of tools
 The Selenium IDE
 Locating UI elements within the browser
 A typical Selenium test harness
Congratulations, you have completed the Selenium User module!
37
Selenium Practitioner
Module
Vijay Ramaswamy
Test Architect & Consultant
Software you will need
 Mozilla Firefox
 Selenium IDE plugin
 Any additional browser such as Google Chrome or Microsoft Edge/IE
 Java and Eclipse (or any other IDE of your choice)
 JUnit and TestNG plugins for Eclipse
 Subversion / Git for version control
 Apache Ant / Maven
 Selenium WebDriver
 Java libraries
 Browser drivers (as required)
39
Chapter I
(2 hours)
40
In this chapter…
 An overview of WebDriver:
 An introduction to WebDriver
 The WebDriver API and relevant commands
 Test execution using WebDriver
41
An introduction to WebDriver (~15 mins)
 W3C standard (draft) for web browser automation
 Wide array of supported programming languages to choose from:
 Java
 C#
 Ruby
 Python
 JavaScript (Node.js)
 3rd party implementations for Perl, PHP, Haskell, etc.
42
An introduction to WebDriver (contd.)
 Support for most browsers out there, with direct support from the browser
manufacturers:
 Mozilla GeckoDriver
 Google ChromeDriver
 InternetExplorerDriver (implemented directly by the WebDriver team)
 Microsoft EdgeDriver
 Apple SafariDriver
 OperaDriver
43
An introduction to WebDriver (contd.)
 Support for “headless” browsers:
 HtmlUnitDriver (based on the HtmlUnit browser)
 GhostDriver (based on the PhantomJS browser)
 One of WebDriver’s key selling points is the ability to reuse a single test script
across any of these supported browsers, with very minimal or no change to
the script itself
 In addition, WebDriver also enables the reuse of test scripts across platforms
including Windows, Linux and Mac (by virtue of the platform independent
nature of the underlying language such as Java)
44
The WebDriver API and relevant
commands (~45 mins)
 Instantiating a WebDriver object
 The “WebElement”:
 A generic interface that represents any UI element on a web page
 Identified using “locators” and the “By” API
 Performing user actions within the browser:
 Clicking, typing, etc.
45
The WebDriver API and relevant
commands (contd.)
 Handling different UI elements:
 Textboxes, checkboxes, lists, etc.
 Other operations:
 Navigating to a URL -> the get() API
 Maximizing the browser -> the manage().window() API
 Reading data from a web page -> the getText() API
 Closing the browser -> the quit() API
46
Test execution using WebDriver (~60 mins)
 Choose your test runner:
 JUnit & TestNG are most commonly used
 You could write your own runner if required
 Execute your tests on multiple browsers and platforms:
 Start with defining your strategy around multi-browser and multi-platform testing
 Leverage data analytics to identify the list of browser/platform combinations that
are most used by end users
47
Test execution using WebDriver (~60 mins)
 Note that you don’t need to replicate all your tests on all identified
browser/platform combinations:
 One approach is to distribute your tests equally between all identified browser-platform
combinations
 E.g.: 100 total tests, 20 test each on 5 different browser/platform combinations
 Another approach is to identify a core subset of tests that will be replicated across all
browser-platform combinations
 The test strategy for responsive web applications should include mobile browsers
and platforms as well -> more on this in a forthcoming module
48
Test execution using WebDriver (contd.)
 The DesiredCapabilities API:
 Used to specify the test’s expectations from the browser driver that it interacts
with
 Expectations include the browser version, platform, proxy configuration, etc.
 Most capabilities are relevant to all the browser drivers
 However, individual browser drivers may have browser-specific capabilities as
appropriate
 Emulating mobile browsers using ChromeDriver:
 Good example of Chrome specific DesiredCapabilities
49
Test execution using WebDriver (contd.)
 Test reporting:
 WebDriver does not have any reporting capabilities built-in
 Test frameworks such as JUnit & TestNG include some basic reporting capabilities
 Reporting plugins such as ReportNG could be used in conjunction with these
frameworks if required
 It is common for teams to write their own reporting plugins to provide more
visually appealing and user-friendly reports
50
Sample exercises
 Automate at least 2 workflows on any of the demo websites using WebDriver
 Execute the scripts on at least 3 different browsers, including 1 headless
browser
 Execute the scripts on an emulated mobile device using Chrome
 Refer to the autopia4j framework’s WebDriverFactory to see code samples for
working with various browsers, and leveraging the DesiredCapabilities API as
appropriate
51
Chapter II
(2 hours)
52
In this chapter…
 Test design patterns:
 Data driven automation
 Keyword driven automation
 Page Object Model
53
Design patterns: An introduction (~5 mins)
 A design pattern is a general repeatable solution to a commonly occurring problem
in software design
 A design pattern isn't a finished design that can be transformed directly into code –
it is a description or template for how to solve a problem that can be used in
many different situations
 Some commonly used design patterns include the Factory pattern, Singleton
pattern, Builder pattern, etc.
 As automation testing has evolved over the years, a number of design patterns
have come up within the testing domain as well, which are collectively known as
test design patterns
 The next few slides introduce some of the commonly used test design patterns,
such as data driven automation, keyword driven automation, and page object
model
54
Test design patterns: Data driven
automation (~10 mins)
 Involves externalizing the test data from the automation script into a tabular format
(usually into an Excel sheet, although other formats such as XML, CSV, databases, etc.
may also be used)
 Benefits:
» Separation of concerns -> the data and scripts are not mixed into each other
» End users can easily change the test data without modifying the scripts
» The same script can be executed with multiple rows of test data
» Reasonably simple to implement, and has a minimal learning curve
55
Test design patterns: Data driven
automation (contd.)
 Things to watch out for:
» End users should ensure that the data inputs are specified in the format expected
by the script, otherwise, the results can be unexpected
» Test engineers should be wary of sharing data between positive and negative
scenarios, since the expected results are probably completely different -> Always
maintain separate scripts and separate test data in such situations
 Refer to the autopia4j reference framework for some examples
56
Test design patterns: Keyword driven
automation (~15 mins)
 Involves building test scripts using a set of custom keywords in a tabular
format (typically Excel) – hence also known as the table-driven approach
 Keywords can be low level (representing elemental user actions) or high level
(representing business processes), and are implemented in code by an
automation engineer
 Selenese is a great example of low level keyword driven automation
 Given below is a simple example of high level keyword driven automation:
57
Test Case Keyword1 Keyword2 Keyword3 Keyword4
TestCashDepositOnNewAccount Login CreateAccount DepositCash VerifyBalance
Test design patterns: Keyword driven
automation (contd.)
 Thoughts on low level keyword driven automation:
 The benefit is that it results in highly readable scripts and has a minimal learning
curve
 However, this approach does not scale beyond all but the simplest of projects,
primarily because low level keywords can never match up to a full blown
programming language!
58
Test design patterns: Keyword driven
automation (contd.)
 Thoughts on high level keyword driven automation:
 Fairly widely used in the industry, and was the precursor to BDD (Behavior Driven
Development) style frameworks such as Cucumber
 On the flip side, it may be slightly frustrating for programmers and automation
engineers to work with keywords in spreadsheets as opposed to directly working
with code
 Refer to the autopia4j reference framework for some examples
59
Test design patterns: Page Object Model
(~90 mins)
 Separation of concerns -> The tests and their implementation are separated
into different layers of code
 All user interactions with the application under test are managed using
separate classes, organized based on the pages of your application:
 A class which handles all user interactions with a given page is known as a “page
class”:
 Each user interaction should be implemented as a separate method within the class
60
Test design patterns: Page Object Model
(contd.)
 Any WebDriver related code should be inside a page class:
 It is usual best practice to externalize all locators as “By” objects at a class level, so that
they can be reused across all methods within the class
 It is also recommended to follow intuitive naming conventions for such “By” objects, such
as “txt” for textboxes, “btn” for buttons, and so on…
 Every method within a page class should return another page object, depending on
the outcome of the method:
 For example, the clickUserRegistrationLink() method should return a
“UserRegistrationPage” object
 This means that you will need separate methods for scenarios such as a valid and an
invalid login -> since their outcomes lead to different pages
61
Test design patterns: Page Object Model
(contd.)
 It is common practice to define a “MasterPage” class which represents UI elements
common across all pages of the application, for instance, menu bars, sign out links,
etc.
 All page classes will need to inherit from this “MasterPage” so that such common
functionality is accessible from all pages
 It is recommended to split up large pages into multiple classes. For example, a
page which contains 5 different tabs may be implemented as 5 separate classes.
This helps to organize your page classes better.
62
Test design patterns: Page Object Model
(contd.)
 Test scripts define the high level business logic, and delegate all the
corresponding implementation to page classes:
 Tests create instances of page classes, known as “page objects”
 Tests don’t directly contain any WebDriver code
 Validations (Assertions) are performed directly within the tests, and not within the
page classes:
 However, the page classes can expose methods which perform relevant validations and
return a true/false result, which can be subsequently used within an assertion
 WebDriver has a “PageFactory” API which provides some in-built support for
this design pattern:
 However, I personally do not recommend using it
63
Sample exercises
 Refactor the scripts that you wrote in the previous exercise to use the page
object model
 Learn to debug test scripts by using Eclipse features such as Step into, Step
over, Breakpoints, Watch variables, etc.
 Discuss the pros and cons of various test design patterns
64
Module recap
In this module, you learnt:
 An overview of WebDriver
 Test design patterns
Congratulations, you have completed the Selenium Practitioner module!
65
Selenium Expert Module
Vijay Ramaswamy
Test Architect & Consultant
Software you will need
 Mozilla Firefox
 Selenium IDE plugin
 Any additional browser such as Google Chrome or Microsoft Edge/IE
 Java and Eclipse (or any other IDE of your choice)
 JUnit and TestNG plugins for Eclipse
 Subversion / Git for version control
 Apache Ant / Apache Maven
 Selenium WebDriver:
 Java libraries
 Browser drivers (as required)
67
Chapter I
(2 hours)
68
In this chapter…
 Special considerations while using WebDriver:
 Synchronization
 Handling alerts, popup windows and frames
 Executing multiple tests in parallel
 Miscellaneous topics – Screenshots, Advanced user interactions
69
Synchronization (~30 mins)
 “Synchronizing” an automated script with the application being tested, by
waiting for the page to load, or waiting for a specific object to load
 Most of the time, WebDriver is intelligent enough to automatically wait for
pages to load
 However, AJAX can sometimes cause pages to keep loading in the background,
which may not be detected by WebDriver
 AJAX can also be used to dynamically load or display specific objects within a
web page, without having to reload the entire page
 This necessitates the script developer to introduce wait times as suitable
 There are 2 kinds of waits supported by WebDriver – implicit and explicit
70
Synchronization (contd.)
 Implicit waits:
 Automatically wait for the specified period of time whenever the script attempts
to find a UI element
 Configured as a one-time setting, that remains active during the entire lifetime of
the driver object (until the quit() method is called)
 Implemented using the “driver.manage().timeouts()” API:
 The “implicitlyWait()” and “pageLoadTimeout()” methods
 Typically applied within the test script’s setup method
71
Synchronization (contd.)
 Explicit waits:
 Wait times configured by a script developer at specific points within the test execution
 Can be used multiple times as required within the script
 Wait for a specified period of time -> Thread.sleep()
 Generally not recommended
 Wait for a specified condition to occur -> The “WebDriverWait” and
“ExpectedConditions” API’s:
 Wait for an element to load
 Wait for an element to become visible
 Wait for an element to get enabled
 Using implicit and explicit waits together leads to the wait times getting added to
one another
72
Handling alerts (~15 mins)
 Alerts are dialog boxes typically used to warn the user, or get the user’s
confirmation before proceeding with an irrevocable user operation (such as a
deletion)
 Alerts are not web pages – they are typically implemented using the
underlying operating system such as Windows, Mac or Linux
 By default, WebDriver “sees” UI elements on the main page only; use the
“driver.switchTo().alert()” API to point WebDriver at the alert box
 Use the “accept()” and “dismiss()” methods to interact with the alert box
73
Handling popup windows (~15 mins)
 Popup windows are web pages that open as child pages to the main page
 Each window is assigned a unique “handle” by the browser:
 Sample window handle (Chrome): “CDwindow-8614d64d-8beb-489d-baca-
b76a543e931b”
 Use the “driver.getWindowHandles()” API to get a list of handles
corresponding to all windows currently open
 Wait for the popup to appear before calling this method!
74
Handling popup windows (contd.)
 By default, WebDriver “sees” UI elements on the main page only; use the
“driver.switchTo().window()” API along with the corresponding window handle
to point WebDriver at popup windows other than the main page
 WebDriver also allows you to switch using the window name instead of the
window handle:
 The window name is specified by the developer of the web page –> use your
browser dev tools to look for the window name
 The window name is specified as one of the inputs (the 2nd one) to the JavaScript
“window.open()” method – this function is typically called within the “onClick”
event of the UI element which causes the popup to appear
75
Handling frames (~15 mins)
 A frame is an isolated section within a web page, with the ability to load
content independent of other frames on the same page
 Frames are implemented using the <frame> or <iframe> tags within HTML
 WebDriver treats frames just like any other UI element -> Use
“driver.findElement()” along with a suitable locator to identify a frame object
 By default, WebDriver “sees” UI elements on the main page only; use the
“driver.switchTo().frame()” API along with the frame identified as a
“WebElement” to point WebDriver at specific frames within the main page
76
Executing multiple tests in parallel (~30
mins)
 WebDriver is probably the only automation tool that supports execution of
multiple tests in parallel (on a single machine):
 Parallel execution works even while using different browsers together
 Screenshots get captured just fine, even while running tests in parallel!
 Tests can be executed in parallel using Java multi-threaded programming
 Option 1: Use Java thread pools to run your tests
 Option 2: Use TestNG’s in-built capabilities for multi-threaded execution
77
Executing multiple tests in parallel
(contd.)
 Things to remember:
 WebDriver is NOT thread-safe:
 This means that a single driver instance cannot be shared across multiple threads -> WebDriver is
deliberately designed this way
 Use techniques such as “ThreadLocal” to ensure that each thread has its own ISOLATED
WebDriver instance
 Be wary of using static fields within your tests -> Remember that static fields are shared
across all threads:
 If a static field is updated by one thread, all other threads will see the updated value. This could
cause unexpected results unless handled carefully.
 Gotchas while using IE:
 The IE Driver may require the browser to be in focus during execution
 This could cause problems while running tests in parallel on IE and another browser
78
Miscellaneous topics (~15 mins)
 Taking screenshots during script execution:
 Cast the WebDriver object to a “TakesScreenshot” object
 Use the “getScreenshotAs()” API, in conjunction with a suitable output type
 The most common output type is a file
 Advanced user interactions – The Actions API:
 Mouse interactions -> The moveToElement() (mouse overs), dragAndDrop(),
doubleClick() API’s
 Keyboard interactions -> The keyDown(), keyUp() API’s
79
Sample exercises
 Automate a sample workflow on any application, and apply the following
concepts:
 Synchronization
 Screenshots
 Frame and popup window handling
 Run the workflow that you automated on 2 or more browsers in parallel
80
Chapter II
(2 hours)
81
In this chapter…
 A peek inside the WebDriver architecture
 Working with RemoteWebDriver
 A deep-dive into Selenium Grid
82
A peek inside the WebDriver architecture (~15 mins)
83
WebDriver
Interface
GeckoDriver
ChromeDriver
EdgeDriver
InternetExplorerDriver
chromedriver.exe
IEDriverServer.exe
Chrome
browser
IE
browser
Firefox
browser
Test script SafariDriver
OperaDriver
GhostDriver
RemoteWebDriver
AppiumDriver
geckodriver.exe
operadriver.exe
phantomjs.exe
<Selenium
server>
Any remote
browser
PhantomJS
browser
Opera
browser
Safari
browser
<Appium server>
Mobile
devices
Edge browserMicrosoftWebDriver.exe
<Embedded driver within
Safari browser>
<Browser
driver.exe>
Client side Server side
HTTP Request
/ Response
A peek inside the WebDriver architecture (contd.)
 Client server based architecture, http based communication
 Test scripts represent the client side; the individual browser drivers represent
the server side
 Servers are auto-started and auto-stopped by clients:
 Glitches in test code may sometimes prevent servers from shutting down properly -
> these remain persistent in memory and need to be manually killed
 Each programming language supported by WebDriver is in effect a separate
implementation of the client side
84
A peek inside the WebDriver architecture (contd.)
 On the other hand, the server side needs only 1 implementation, and can be
built on any technology as desired by the respective browser manufacturers
 RemoteWebDriver is a special implementation of WebDriver, which enables
the client and server to exist on different machines within the same network
 It is built using Java
 Note that the server as well as the client are bundled into the same “selenium-
standalone-server.jar” file!
 Appium is another special implementation of WebDriver, which enables test
scripts to be executed on mobile devices
 It is built using Node.js
85
A peek inside the WebDriver architecture (contd.)
 Going forward into Selenium 3.0, release cycles will be decoupled for the
client and server sides:
 Server side releases will typically be synchronized with the individual browser
release cycles, and will be more frequent
 Client side releases will relate to new capabilities getting added to WebDriver, and
will be relatively less frequent
86
Working with RemoteWebDriver (~30 mins)
 Starting the server on the remote machine:
 Start the selenium server by running the Selenium standalone JAR file from the
command line:
 java –jar “selenium-standalone-server-3.0.1.jar”
 The server starts on port 4444 by default. You can change it using the “-port”
switch
 java –jar “selenium-standalone-server-3.0.1.jar” –port 6789
 Specify the location of browser driver exe files by using the “-D” switch along with
the name of the system property to be set:
 java –Dwebdriver.chrome.driver=“C:webdriverchromedriver.exe” –jar “selenium-
standalone-server-3.0.1.jar”
 View the server console:
 Use the URL: http://server:port/wd/hub/static/resource/hub.html
87
Working with RemoteWebDriver (contd.)
 Pointing your script (client) to the server:
 Instantiate a “RemoteWebDriver” object using the new keyword
 Specify the remote server URL while instantiating the RemoteWebDriver:
 Use the URL: http://server:port/wd/hub
 Specify server side expectations using the “DesiredCapabilities” API
 Browser, browser version, platform, etc. to be used on the remote machine
 Remember to properly close out all sessions using the quit() API!
 Sample exercise:
 Execute any of your scripts on a remote machine -> work in pairs and run on each
other’s machine
88
A deep-dive into Selenium Grid (~60 mins)
 What is Selenium Grid?
 A mechanism to scale test execution by distributing it across multiple machines
 An extension of the RemoteWebDriver, in which the selenium server plays special
roles known as “hub” and “node”
 How does the grid work?
 Hub:
 Centralized controller for the grid
 One stop destination for all test scripts
 Delegates test execution to connected nodes based on availability
 Does not participate directly towards test execution
89
A deep-dive into Selenium Grid (contd.)
 How does the grid work (contd.)?
 Node(s):
 Individual server instances managed by the hub
 A single node can handle multiple instances of multiple browsers in parallel, depending on
how it is configured
 E.g.: 5 instances of Chrome and 5 instances of Firefox
 It is possible to run multiple nodes on the same machine, by using different ports
 It is possible to run a hub and a node together on the same machine!
90
A deep-dive into Selenium Grid (contd.)
 Setting up the grid:
 Starting the hub and node(s):
 Run selenium server from the command line
 Use the “-role” switch to indicate whether the server needs to run as a hub or as a node
 If the server is running under the role of a node, you need to “register” it to the central
hub using the “-hub” switch
91
A deep-dive into Selenium Grid (contd.)
 Setting up the grid (contd.):
 Configuring the capabilities of a given node:
 Every grid node automatically detects all browsers installed on the machine and
configures itself as appropriate
 This can be overridden manually using one of the following methods:
 Using various switches directly on the command line
 Using the “-nodeConfig” flag to read the capabilities from a JSON configuration file
 Configure the “maxInstances” flag depending on the number of parallel instances the node
machine can handle without running out of memory or crashing:
 Remember that IE has issues with parallel execution; this means that you should ideally set
“maxInstances” to 1 whenever you setup an IE node, and avoid using the node with any other
browsers in parallel
92
A deep-dive into Selenium Grid (contd.)
 Setting up the grid (contd.):
 Viewing the Grid console:
 Access via the browser @ http://hub-server:port/grid/console
 The console displays the list of nodes being managed by the hub, along with their
respective capabilities
93
A deep-dive into Selenium Grid (contd.)
 Running scripts against the grid:
 Use the DesiredCapabilities and RemoteWebDriver APIs
 Specify the hub’s URL while instantiating the RemoteWebDriver
 Achieve parallelism using Java thread pools or TestNG as explained in the previous
session
 Cloud based grid solutions:
 Sauce Labs
 BrowserStack
 SmartBear CrossBrowserTesting
94
Sample exercises
 Setup a Selenium Grid
 Work in groups of 3 or 4
 Execute your scripts on the Grid
 Optional: Sign up for a trial on Sauce Labs and execute your scripts against
the cloud
95
Module recap
In this module, you learnt:
 Special considerations while using WebDriver
 A peek inside the WebDriver architecture
 Working with RemoteWebDriver
 A deep-dive into Selenium Grid
Congratulations, you have completed the Selenium Expert module!
96
THANK YOU!
Vijay Ramaswamy
Test Architect & Consultant
97

More Related Content

What's hot

An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
Anuraj S.L
 
Automation Testing using Selenium
Automation Testing using SeleniumAutomation Testing using Selenium
Automation Testing using Selenium
Naresh Chintalcheru
 
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Simplilearn
 
Selenium test automation
Selenium test automationSelenium test automation
Selenium test automation
Srikanth Vuriti
 
QSpiders - Automation using Selenium
QSpiders - Automation using SeleniumQSpiders - Automation using Selenium
QSpiders - Automation using Selenium
Qspiders - Software Testing Training Institute
 
Selenium
SeleniumSelenium
Selenium
Batch2016
 
Automation Testing using Selenium Webdriver
Automation Testing using Selenium WebdriverAutomation Testing using Selenium Webdriver
Automation Testing using Selenium Webdriver
Pankaj Biswas
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
Tzirla Rozental
 
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
Simplilearn
 
Introduction to Selenium Automation
Introduction to Selenium AutomationIntroduction to Selenium Automation
Introduction to Selenium Automation
Mindfire Solutions
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
Aneesh Rangarajan
 
Selenium
SeleniumSelenium
Selenium
Adam Goucher
 
Selenium locators: ID, Name, xpath, CSS Selector advance methods
Selenium locators: ID, Name,  xpath, CSS Selector advance methodsSelenium locators: ID, Name,  xpath, CSS Selector advance methods
Selenium locators: ID, Name, xpath, CSS Selector advance methods
Pankaj Dubey
 
Automated Web Testing Using Selenium
Automated Web Testing Using SeleniumAutomated Web Testing Using Selenium
Automated Web Testing Using Selenium
Weifeng Zhang
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
Mindfire Solutions
 
Selenium-Locators
Selenium-LocatorsSelenium-Locators
Selenium-Locators
Mithilesh Singh
 
Introduction to selenium
Introduction to seleniumIntroduction to selenium
Introduction to selenium
Archana Krushnan
 
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Simplilearn
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Edureka!
 

What's hot (20)

An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
 
Automation Testing using Selenium
Automation Testing using SeleniumAutomation Testing using Selenium
Automation Testing using Selenium
 
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
 
Selenium test automation
Selenium test automationSelenium test automation
Selenium test automation
 
QSpiders - Automation using Selenium
QSpiders - Automation using SeleniumQSpiders - Automation using Selenium
QSpiders - Automation using Selenium
 
Selenium
SeleniumSelenium
Selenium
 
Selenium Concepts
Selenium ConceptsSelenium Concepts
Selenium Concepts
 
Automation Testing using Selenium Webdriver
Automation Testing using Selenium WebdriverAutomation Testing using Selenium Webdriver
Automation Testing using Selenium Webdriver
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
 
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
 
Introduction to Selenium Automation
Introduction to Selenium AutomationIntroduction to Selenium Automation
Introduction to Selenium Automation
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 
Selenium
SeleniumSelenium
Selenium
 
Selenium locators: ID, Name, xpath, CSS Selector advance methods
Selenium locators: ID, Name,  xpath, CSS Selector advance methodsSelenium locators: ID, Name,  xpath, CSS Selector advance methods
Selenium locators: ID, Name, xpath, CSS Selector advance methods
 
Automated Web Testing Using Selenium
Automated Web Testing Using SeleniumAutomated Web Testing Using Selenium
Automated Web Testing Using Selenium
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
 
Selenium-Locators
Selenium-LocatorsSelenium-Locators
Selenium-Locators
 
Introduction to selenium
Introduction to seleniumIntroduction to selenium
Introduction to selenium
 
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
 

Similar to Selenium WebDriver training

Selenium Webdriver Interview Questions
Selenium Webdriver Interview QuestionsSelenium Webdriver Interview Questions
Selenium Webdriver Interview Questions
Jai Singh
 
Selenium.pptx
Selenium.pptxSelenium.pptx
Selenium.pptx
orbitprojects
 
Interview question & Answers for 3+ years experienced in Selenium | LearningSlot
Interview question & Answers for 3+ years experienced in Selenium | LearningSlotInterview question & Answers for 3+ years experienced in Selenium | LearningSlot
Interview question & Answers for 3+ years experienced in Selenium | LearningSlot
Learning Slot
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
SpringPeople
 
Test Automation Using Selenium
Test Automation Using SeleniumTest Automation Using Selenium
Test Automation Using Selenium
Nikhil Kapoor
 
Selenium interview-questions-freshers
Selenium interview-questions-freshersSelenium interview-questions-freshers
Selenium interview-questions-freshers
Naga Mani
 
Selenium training
Selenium trainingSelenium training
Selenium training
Shivaraj R
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - Introduction
Amr E. Mohamed
 
Selenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And AnswersSelenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And Answers
Ajit Jadhav
 
Selenium.pptx
Selenium.pptxSelenium.pptx
Selenium.pptx
Pandiya Rajan
 
Test automation using selenium
Test automation using seleniumTest automation using selenium
Test automation using selenium
Cynoteck Technology Solutions Private Limited
 
25 Top Selenium Interview Questions and Answers for 2023.pdf
25 Top Selenium Interview Questions and Answers for 2023.pdf25 Top Selenium Interview Questions and Answers for 2023.pdf
25 Top Selenium Interview Questions and Answers for 2023.pdf
AnanthReddy38
 
selenium-webdriver-interview-questions.pdf
selenium-webdriver-interview-questions.pdfselenium-webdriver-interview-questions.pdf
selenium-webdriver-interview-questions.pdf
AnuragMourya8
 
10071756.ppt
10071756.ppt10071756.ppt
10071756.ppt
Rohit846825
 
Interview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlotInterview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlot
Learning Slot
 
Karate _Framework.ppt
Karate _Framework.pptKarate _Framework.ppt
Karate _Framework.ppt
SamKhan531862
 
Test_Automation using Selenium.ppt
Test_Automation using Selenium.pptTest_Automation using Selenium.ppt
Test_Automation using Selenium.ppt
SamKhan531862
 
Intelligent Testing Tool: Selenium Web Driver
Intelligent Testing Tool: Selenium Web DriverIntelligent Testing Tool: Selenium Web Driver
Intelligent Testing Tool: Selenium Web Driver
IRJET Journal
 

Similar to Selenium WebDriver training (20)

Selenium Webdriver Interview Questions
Selenium Webdriver Interview QuestionsSelenium Webdriver Interview Questions
Selenium Webdriver Interview Questions
 
Selenium.pptx
Selenium.pptxSelenium.pptx
Selenium.pptx
 
Web Testen mit Selenium
Web Testen mit SeleniumWeb Testen mit Selenium
Web Testen mit Selenium
 
Interview question & Answers for 3+ years experienced in Selenium | LearningSlot
Interview question & Answers for 3+ years experienced in Selenium | LearningSlotInterview question & Answers for 3+ years experienced in Selenium | LearningSlot
Interview question & Answers for 3+ years experienced in Selenium | LearningSlot
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
 
Test Automation Using Selenium
Test Automation Using SeleniumTest Automation Using Selenium
Test Automation Using Selenium
 
Selenium interview-questions-freshers
Selenium interview-questions-freshersSelenium interview-questions-freshers
Selenium interview-questions-freshers
 
Selenium training
Selenium trainingSelenium training
Selenium training
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - Introduction
 
Selenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And AnswersSelenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And Answers
 
Selenium.pptx
Selenium.pptxSelenium.pptx
Selenium.pptx
 
Test automation using selenium
Test automation using seleniumTest automation using selenium
Test automation using selenium
 
25 Top Selenium Interview Questions and Answers for 2023.pdf
25 Top Selenium Interview Questions and Answers for 2023.pdf25 Top Selenium Interview Questions and Answers for 2023.pdf
25 Top Selenium Interview Questions and Answers for 2023.pdf
 
selenium-webdriver-interview-questions.pdf
selenium-webdriver-interview-questions.pdfselenium-webdriver-interview-questions.pdf
selenium-webdriver-interview-questions.pdf
 
10071756.ppt
10071756.ppt10071756.ppt
10071756.ppt
 
Interview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlotInterview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlot
 
Karate _Framework.ppt
Karate _Framework.pptKarate _Framework.ppt
Karate _Framework.ppt
 
Test_Automation using Selenium.ppt
Test_Automation using Selenium.pptTest_Automation using Selenium.ppt
Test_Automation using Selenium.ppt
 
Intelligent Testing Tool: Selenium Web Driver
Intelligent Testing Tool: Selenium Web DriverIntelligent Testing Tool: Selenium Web Driver
Intelligent Testing Tool: Selenium Web Driver
 
Selenium
SeleniumSelenium
Selenium
 

Recently uploaded

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 

Recently uploaded (20)

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 

Selenium WebDriver training

  • 2. Course structure 2 Module Topics covered Selenium User • The basics of Selenium • Understanding script execution Selenium Practitioner • Deep-dive into WebDriver • Test design patterns • Understanding basic script development Selenium Expert • Advanced concepts • Understanding “real-world” script development & maintenance
  • 3. Pre-requisites  You will need to be familiar with the Java programming language and Core Java concepts  Familiarity with the basic concepts of version control using Subversion or Git would be useful 3
  • 4. Demo websites for sample exercises  http://automationpractice.com  http://newtours.demoaut.com/  http://web2.0calc.com/  http://demoqa.com/  http://www.way2automation.com 4
  • 5. Reference material  The Selenium official website is the best place to start for learning about Selenium  Navigate to www.seleniumhq.org and click on the Documentation link  Code samples to be referenced throughout this training:  https://github.com/vijkris99/test-framework-basics  Reference Automation Framework (autopia4j):  https://github.com/autopia4j  https://autopia4j.github.io/autopia4j-core-apidocs/index.html  https://autopia4j.github.io/autopia4j-webdriver-apidocs/index.html 5
  • 6. Selenium User Module Vijay Ramaswamy Test Architect & Consultant
  • 7. Software you will need  Chapter I:  Mozilla Firefox  Selenium IDE plugin  Any additional browser such as Google Chrome or Microsoft Edge/IE  Chapter II:  Java and Eclipse (or any other IDE of your choice)  JUnit and TestNG plugins for Eclipse  Subversion / Git for version control  Apache Ant / Apache Maven 7
  • 9. In this chapter…  An introduction to Selenium  The Selenium suite of tools  The Selenium IDE  Locating UI elements within the browser 9
  • 10. An introduction to Selenium (~20 mins)  What is Selenium?  Selenium automates browsers  Supports every major browser out there  Has achieved widespread adoption and has a vibrant community 10
  • 11. An introduction to Selenium (contd.)  Why was it named so?  Mercury is a liquid metal, which can cause great harm to humans (including death) if exposed -> this is commonly referred to as Mercury poisoning  Selenium is a chemical that is considered a possible antidote for Mercury poisoning  At the time that Selenium was created, Mercury was the name of the company which owned a popular automation tool called Quick Test Professional (QTP). Mercury was subsequently taken over by HP.  While QTP (now called UFT) is quite popular in the testing industry, proponents of Selenium have criticized the tool for various reasons. Selenium was created in direct competition to QTP, and that is how it got its name ;) 11
  • 12. An introduction to Selenium (contd.)  A brief history of Selenium:  Selenium 1.0 born @ ThoughtWorks in 2004  WebDriver born @ Google in 2006  Selenium 1.0 merged with WebDriver in 2008, giving rise to Selenium 2.0  Selenium 1.0 deprecated and eventually sunset  What Selenium cannot do:  Cannot send HTTP requests  Cannot interact with embedded objects in web pages, such as videos, java applets, flash, PDF files, etc. 12
  • 13. The Selenium suite of tools (~10 mins)  Selenium IDE:  Integrated Development Environment  Firefox plugin that enables basic Record & Playback  Acts as a useful aid during script development  The only real “tool” within the Selenium suite  Selenium RC:  Initial version of Selenium  RC = Remote Control  Provides an API to automate browsers  Based on proxy injection of JavaScript based commands  Currently deprecated 13
  • 14. The Selenium suite of tools (contd.)  Selenium WebDriver:  Current version of Selenium  Provides an API to automate browsers (completely different from the Selenium RC API!)  Leverages native automation support provided by individual browsers  Selenium Grid:  A mechanism to scale test execution by distributing it across multiple machines 14
  • 15. The Selenium IDE (~30 mins)  Installing the IDE  Using the IDE:  Recording a test script  Playing back a test script  Saving a test script  “Selenese” commands  Assertions and Verifications 15
  • 16. Sample exercises  Record (and save) at least 2 workflows on one of the demo websites  Include Assert/Verify validations as relevant  Ensure that the scripts play back successfully  Discuss the pros and cons of Selenium IDE 16
  • 17. Locating UI elements within the browser (~60 mins)  Selenium identifies UI elements using “locators”:  A locator should uniquely identify the element under consideration  Selenium supports many different kinds of locators -> apply judgement while choosing from among these  Test your locator before using it within a script!  The first step to identifying the locator for a given UI element is to view the HTML source:  Basic method: Right click on the page in your browser -> View Source  Recommended method: Use the development tools available within your browser! 17
  • 18. Locating UI elements within the browser (contd.)  Locating by ID, Name:  Most preferred locator strategy  Can be used only when the element has a unique ID or Name attribute  Locating by LinkText, Partial LinkText:  Another preferred locator strategy  Relevant only for hyperlink elements  Locating by Tag Name, Class Name:  Not used very frequently because these are not unique most of the time 18
  • 19. Locating UI elements within the browser (contd.)  The next 2 locator strategies provide the most advanced capabilities:  This directly translates into higher complexity and longer learning curve  Use these only when all other locator strategies have been exhausted:  It is not “cool” to use advanced locators just for the sake of using them!  Locating by XPath:  A query language used to select specific nodes within an XML document  Provides extensive capabilities to traverse through an XML document as a “tree”  Applicable to web app automation since HTML is a subset of XML 19
  • 20. Locating UI elements within the browser (contd.)  Locating by XPath (contd.):  XPath syntax and examples:  Searching for a specific node within an XML/HTML document  Absolute vs. relative XPaths  Filtering nodes by attributes  Filtering nodes by text  Using regular expressions while filtering nodes  Combining multiple filters together 20
  • 21. Locating UI elements within the browser (contd.)  Locating by XPath (contd.):  Best practices:  Keep XPaths as short as possible -> the longer an XPath is, the more the chances of it being brittle  Avoid using indexes as far as possible -> If a developer moves around UI elements, your XPaths stop working  If an element is not directly identifiable by an XPath, try looking at the element’s parents or siblings -> Chances are, one of those are unique, and you can derive an XPath from that point 21
  • 22. Locating UI elements within the browser (contd.)  Locating by CSS selectors:  CSS = Cascading Style Sheets  Used by web developers to apply UI formatting to web pages  Formatting can be targeted at specific UI elements using selectors:  Element selector: “All level-1 headings (<h1>) should be in blue color”  ID selector: “All elements having ID = ‘danger’ should be highlighted in red”  Class selector: “All elements having class = ‘centered’ should be aligned in the center of the page”  Selenium leverages CSS Selectors to identify UI elements to interact with  CSS selectors reference 22
  • 23. Locating UI elements within the browser (contd.)  In general, CSS selectors and XPath offer a similar set of capabilities, and choosing between the two is often a matter of personal preference:  One minor difference is that CSS selectors tend to be more compact compared to XPaths  All best practices mentioned under the XPath section also apply to CSS selectors 23
  • 24. Sample exercises  Become familiar with the usage of Chrome Dev tools:  Selecting elements  Highlighting elements  Validating your XPath and CSS Selectors  Navigate to one of the demo websites:  Pick any 5 UI elements and identify each of them using at least 2 different locators  Pick any element which does not have a unique ID/Name, and identify it using 3 different XPath expressions  Repeat the same exercise using CSS Selectors  Compare all the selectors used in the above exercises and call out pros and cons of each one 24
  • 25. Sample exercises (contd.)  Open the Selenium IDE:  Edit one of your recorded scripts and add a step using the “Select Target” functionality  Navigate to the relevant page and try to highlight UI elements from your script  Examine the locators generated by the IDE and replace any brittle locators suitably 25
  • 27. In this chapter…  A typical Selenium test harness:  An introduction to testing frameworks  An introduction to build automation tools  An introduction to build automation servers 27
  • 28. An introduction to testing frameworks (~75 mins)  A testing framework provides the basic infrastructure required to design and execute automated test cases, and report on test results  Introduction to JUnit and TestNG:  Popular unit testing frameworks in the Java ecosystem  Use Java annotations to manage the test lifecycle:  JUnit: @Test, @Before, @After, @BeforeClass, @AfterClass  TestNG: @Test, @BeforeMethod, @AfterMethod, @BeforeSuite, @AfterSuite  Use Asserts and Matchers (such as Hamcrest or AssertJ) to validate specific test conditions that may be required as part of your tests 28
  • 29. An introduction to testing frameworks (contd.)  Introduction to JUnit and TestNG (contd.):  Execute tests:  Using Eclipse plug-ins (most common)  Using the command line  Using an XML file (TestNG only)  View test results:  Using Eclipse plug-ins (most common)  Export results to custom formats such as XML or HTML  Out of the box HTML results (TestNG only)  Use Reporter.log() method to send custom messages to test report 29
  • 30. An introduction to testing frameworks (contd.)  Introduction to JUnit and TestNG (contd.):  In summary, a leap ahead from using a simple main() method to run your tests!  Refer to the links on the resources slide to access some sample scripts built using JUnit and TestNG  Selenium does not have a built-in test runner or reporting mechanism:  This is where JUnit/TestNG comes in  Note that Selenium tests are not considered unit tests, although we leverage a unit testing framework 30
  • 31. Sample exercises  Write a simple calculator program, and design white box tests for your program using JUnit or TestNG  Extend your scripts to use Hamcrest matchers or AssertJ  Export one of your scripts to the JUnit or TestNG format from the Selenium IDE  Examine the basic structure of the exported scripts  Become familiar with the clipboard formatting functionality within the Selenium IDE 31
  • 32. An introduction to build automation tools (~15 mins)  A build automation tool automates the creation of a software build, including processes such as compiling, packaging, deploying, running automated tests, etc.  Oversimplified view: A glorified batch file!  Apache Ant and Apache Maven are 2 of the most popular build automation tools in the Java ecosystem  Introduction to Apache Ant:  Ant = Another Neat Tool  Processes build scripts written using XML (typically named build.xml):  Task = Basic commands  Target = Collection of commands to accomplish a specific goal  The JUnit / TestNG tasks 32
  • 33. An introduction to build automation tools (contd.)  Introduction to Apache Ant (contd.):  Installing Ant:  Eclipse comes pre-installed with the Ant plugin  If you want to run Ant from the command line, you need to install it separately:  Ensure that the “JAVA_HOME”, “ANT_HOME” and “Path” environment variables are configured as appropriate  Running an Ant script:  From the command line: Use the “ant” command  From Eclipse: Right click on build.xml -> Run As -> Ant build  From a build automation server such as Jenkins: Refer next slide  Introduction to Apache Maven:  Refer to my presentation on Maven Basics 33
  • 34. An introduction to build automation servers (~10 mins)  A build automation server:  Implements the build automation process on a web based server, with the aim of centralizing the build for the entire team  Offers a browser based UI to enable users to configure their builds as required  Typically integrates with one or more build automation tools, and usually does not attempt to directly automate the build process  Provides additional capabilities such as scheduled builds, auto-triggered builds, integration with source code repositories, etc., which makes them indispensable towards implementing Continuous Integration and Continuous Delivery  Some of the popular build automation servers out there include Jenkins/Hudson, Travis CI, Bamboo, MS TFS, TeamCity, etc. 34
  • 35. An introduction to build automation servers (contd.)  Introduction to Jenkins:  Open source server with a vibrant community  Fork of the Hudson project  Vast ecosystem of plugins that enable integration with various version control tools, build automation tools, testing tools, etc.  Projects are managed as “jobs”, which typically consist of 3 parts:  Build triggers  Build steps  Post-build actions  Jobs can be managed in a distributed fashion across multiple machines, using a master-slave architecture 35
  • 36. An introduction to build automation servers (contd.)  Executing an Ant build from Jenkins:  Ensure that Ant is setup properly on the Jenkins host machine (You should be able to run Ant from the command line)  Configure JDK and Ant within the Jenkins System Configuration  Create a new job  Point the job to your source code repository  Add “Invoke Ant” as a build step  Build your job!  Sample exercise:  Install Jenkins and try setting up a job to run your automated scripts 36
  • 37. Module recap In this module, you learnt:  An introduction to Selenium  The Selenium suite of tools  The Selenium IDE  Locating UI elements within the browser  A typical Selenium test harness Congratulations, you have completed the Selenium User module! 37
  • 39. Software you will need  Mozilla Firefox  Selenium IDE plugin  Any additional browser such as Google Chrome or Microsoft Edge/IE  Java and Eclipse (or any other IDE of your choice)  JUnit and TestNG plugins for Eclipse  Subversion / Git for version control  Apache Ant / Maven  Selenium WebDriver  Java libraries  Browser drivers (as required) 39
  • 41. In this chapter…  An overview of WebDriver:  An introduction to WebDriver  The WebDriver API and relevant commands  Test execution using WebDriver 41
  • 42. An introduction to WebDriver (~15 mins)  W3C standard (draft) for web browser automation  Wide array of supported programming languages to choose from:  Java  C#  Ruby  Python  JavaScript (Node.js)  3rd party implementations for Perl, PHP, Haskell, etc. 42
  • 43. An introduction to WebDriver (contd.)  Support for most browsers out there, with direct support from the browser manufacturers:  Mozilla GeckoDriver  Google ChromeDriver  InternetExplorerDriver (implemented directly by the WebDriver team)  Microsoft EdgeDriver  Apple SafariDriver  OperaDriver 43
  • 44. An introduction to WebDriver (contd.)  Support for “headless” browsers:  HtmlUnitDriver (based on the HtmlUnit browser)  GhostDriver (based on the PhantomJS browser)  One of WebDriver’s key selling points is the ability to reuse a single test script across any of these supported browsers, with very minimal or no change to the script itself  In addition, WebDriver also enables the reuse of test scripts across platforms including Windows, Linux and Mac (by virtue of the platform independent nature of the underlying language such as Java) 44
  • 45. The WebDriver API and relevant commands (~45 mins)  Instantiating a WebDriver object  The “WebElement”:  A generic interface that represents any UI element on a web page  Identified using “locators” and the “By” API  Performing user actions within the browser:  Clicking, typing, etc. 45
  • 46. The WebDriver API and relevant commands (contd.)  Handling different UI elements:  Textboxes, checkboxes, lists, etc.  Other operations:  Navigating to a URL -> the get() API  Maximizing the browser -> the manage().window() API  Reading data from a web page -> the getText() API  Closing the browser -> the quit() API 46
  • 47. Test execution using WebDriver (~60 mins)  Choose your test runner:  JUnit & TestNG are most commonly used  You could write your own runner if required  Execute your tests on multiple browsers and platforms:  Start with defining your strategy around multi-browser and multi-platform testing  Leverage data analytics to identify the list of browser/platform combinations that are most used by end users 47
  • 48. Test execution using WebDriver (~60 mins)  Note that you don’t need to replicate all your tests on all identified browser/platform combinations:  One approach is to distribute your tests equally between all identified browser-platform combinations  E.g.: 100 total tests, 20 test each on 5 different browser/platform combinations  Another approach is to identify a core subset of tests that will be replicated across all browser-platform combinations  The test strategy for responsive web applications should include mobile browsers and platforms as well -> more on this in a forthcoming module 48
  • 49. Test execution using WebDriver (contd.)  The DesiredCapabilities API:  Used to specify the test’s expectations from the browser driver that it interacts with  Expectations include the browser version, platform, proxy configuration, etc.  Most capabilities are relevant to all the browser drivers  However, individual browser drivers may have browser-specific capabilities as appropriate  Emulating mobile browsers using ChromeDriver:  Good example of Chrome specific DesiredCapabilities 49
  • 50. Test execution using WebDriver (contd.)  Test reporting:  WebDriver does not have any reporting capabilities built-in  Test frameworks such as JUnit & TestNG include some basic reporting capabilities  Reporting plugins such as ReportNG could be used in conjunction with these frameworks if required  It is common for teams to write their own reporting plugins to provide more visually appealing and user-friendly reports 50
  • 51. Sample exercises  Automate at least 2 workflows on any of the demo websites using WebDriver  Execute the scripts on at least 3 different browsers, including 1 headless browser  Execute the scripts on an emulated mobile device using Chrome  Refer to the autopia4j framework’s WebDriverFactory to see code samples for working with various browsers, and leveraging the DesiredCapabilities API as appropriate 51
  • 53. In this chapter…  Test design patterns:  Data driven automation  Keyword driven automation  Page Object Model 53
  • 54. Design patterns: An introduction (~5 mins)  A design pattern is a general repeatable solution to a commonly occurring problem in software design  A design pattern isn't a finished design that can be transformed directly into code – it is a description or template for how to solve a problem that can be used in many different situations  Some commonly used design patterns include the Factory pattern, Singleton pattern, Builder pattern, etc.  As automation testing has evolved over the years, a number of design patterns have come up within the testing domain as well, which are collectively known as test design patterns  The next few slides introduce some of the commonly used test design patterns, such as data driven automation, keyword driven automation, and page object model 54
  • 55. Test design patterns: Data driven automation (~10 mins)  Involves externalizing the test data from the automation script into a tabular format (usually into an Excel sheet, although other formats such as XML, CSV, databases, etc. may also be used)  Benefits: » Separation of concerns -> the data and scripts are not mixed into each other » End users can easily change the test data without modifying the scripts » The same script can be executed with multiple rows of test data » Reasonably simple to implement, and has a minimal learning curve 55
  • 56. Test design patterns: Data driven automation (contd.)  Things to watch out for: » End users should ensure that the data inputs are specified in the format expected by the script, otherwise, the results can be unexpected » Test engineers should be wary of sharing data between positive and negative scenarios, since the expected results are probably completely different -> Always maintain separate scripts and separate test data in such situations  Refer to the autopia4j reference framework for some examples 56
  • 57. Test design patterns: Keyword driven automation (~15 mins)  Involves building test scripts using a set of custom keywords in a tabular format (typically Excel) – hence also known as the table-driven approach  Keywords can be low level (representing elemental user actions) or high level (representing business processes), and are implemented in code by an automation engineer  Selenese is a great example of low level keyword driven automation  Given below is a simple example of high level keyword driven automation: 57 Test Case Keyword1 Keyword2 Keyword3 Keyword4 TestCashDepositOnNewAccount Login CreateAccount DepositCash VerifyBalance
  • 58. Test design patterns: Keyword driven automation (contd.)  Thoughts on low level keyword driven automation:  The benefit is that it results in highly readable scripts and has a minimal learning curve  However, this approach does not scale beyond all but the simplest of projects, primarily because low level keywords can never match up to a full blown programming language! 58
  • 59. Test design patterns: Keyword driven automation (contd.)  Thoughts on high level keyword driven automation:  Fairly widely used in the industry, and was the precursor to BDD (Behavior Driven Development) style frameworks such as Cucumber  On the flip side, it may be slightly frustrating for programmers and automation engineers to work with keywords in spreadsheets as opposed to directly working with code  Refer to the autopia4j reference framework for some examples 59
  • 60. Test design patterns: Page Object Model (~90 mins)  Separation of concerns -> The tests and their implementation are separated into different layers of code  All user interactions with the application under test are managed using separate classes, organized based on the pages of your application:  A class which handles all user interactions with a given page is known as a “page class”:  Each user interaction should be implemented as a separate method within the class 60
  • 61. Test design patterns: Page Object Model (contd.)  Any WebDriver related code should be inside a page class:  It is usual best practice to externalize all locators as “By” objects at a class level, so that they can be reused across all methods within the class  It is also recommended to follow intuitive naming conventions for such “By” objects, such as “txt” for textboxes, “btn” for buttons, and so on…  Every method within a page class should return another page object, depending on the outcome of the method:  For example, the clickUserRegistrationLink() method should return a “UserRegistrationPage” object  This means that you will need separate methods for scenarios such as a valid and an invalid login -> since their outcomes lead to different pages 61
  • 62. Test design patterns: Page Object Model (contd.)  It is common practice to define a “MasterPage” class which represents UI elements common across all pages of the application, for instance, menu bars, sign out links, etc.  All page classes will need to inherit from this “MasterPage” so that such common functionality is accessible from all pages  It is recommended to split up large pages into multiple classes. For example, a page which contains 5 different tabs may be implemented as 5 separate classes. This helps to organize your page classes better. 62
  • 63. Test design patterns: Page Object Model (contd.)  Test scripts define the high level business logic, and delegate all the corresponding implementation to page classes:  Tests create instances of page classes, known as “page objects”  Tests don’t directly contain any WebDriver code  Validations (Assertions) are performed directly within the tests, and not within the page classes:  However, the page classes can expose methods which perform relevant validations and return a true/false result, which can be subsequently used within an assertion  WebDriver has a “PageFactory” API which provides some in-built support for this design pattern:  However, I personally do not recommend using it 63
  • 64. Sample exercises  Refactor the scripts that you wrote in the previous exercise to use the page object model  Learn to debug test scripts by using Eclipse features such as Step into, Step over, Breakpoints, Watch variables, etc.  Discuss the pros and cons of various test design patterns 64
  • 65. Module recap In this module, you learnt:  An overview of WebDriver  Test design patterns Congratulations, you have completed the Selenium Practitioner module! 65
  • 66. Selenium Expert Module Vijay Ramaswamy Test Architect & Consultant
  • 67. Software you will need  Mozilla Firefox  Selenium IDE plugin  Any additional browser such as Google Chrome or Microsoft Edge/IE  Java and Eclipse (or any other IDE of your choice)  JUnit and TestNG plugins for Eclipse  Subversion / Git for version control  Apache Ant / Apache Maven  Selenium WebDriver:  Java libraries  Browser drivers (as required) 67
  • 69. In this chapter…  Special considerations while using WebDriver:  Synchronization  Handling alerts, popup windows and frames  Executing multiple tests in parallel  Miscellaneous topics – Screenshots, Advanced user interactions 69
  • 70. Synchronization (~30 mins)  “Synchronizing” an automated script with the application being tested, by waiting for the page to load, or waiting for a specific object to load  Most of the time, WebDriver is intelligent enough to automatically wait for pages to load  However, AJAX can sometimes cause pages to keep loading in the background, which may not be detected by WebDriver  AJAX can also be used to dynamically load or display specific objects within a web page, without having to reload the entire page  This necessitates the script developer to introduce wait times as suitable  There are 2 kinds of waits supported by WebDriver – implicit and explicit 70
  • 71. Synchronization (contd.)  Implicit waits:  Automatically wait for the specified period of time whenever the script attempts to find a UI element  Configured as a one-time setting, that remains active during the entire lifetime of the driver object (until the quit() method is called)  Implemented using the “driver.manage().timeouts()” API:  The “implicitlyWait()” and “pageLoadTimeout()” methods  Typically applied within the test script’s setup method 71
  • 72. Synchronization (contd.)  Explicit waits:  Wait times configured by a script developer at specific points within the test execution  Can be used multiple times as required within the script  Wait for a specified period of time -> Thread.sleep()  Generally not recommended  Wait for a specified condition to occur -> The “WebDriverWait” and “ExpectedConditions” API’s:  Wait for an element to load  Wait for an element to become visible  Wait for an element to get enabled  Using implicit and explicit waits together leads to the wait times getting added to one another 72
  • 73. Handling alerts (~15 mins)  Alerts are dialog boxes typically used to warn the user, or get the user’s confirmation before proceeding with an irrevocable user operation (such as a deletion)  Alerts are not web pages – they are typically implemented using the underlying operating system such as Windows, Mac or Linux  By default, WebDriver “sees” UI elements on the main page only; use the “driver.switchTo().alert()” API to point WebDriver at the alert box  Use the “accept()” and “dismiss()” methods to interact with the alert box 73
  • 74. Handling popup windows (~15 mins)  Popup windows are web pages that open as child pages to the main page  Each window is assigned a unique “handle” by the browser:  Sample window handle (Chrome): “CDwindow-8614d64d-8beb-489d-baca- b76a543e931b”  Use the “driver.getWindowHandles()” API to get a list of handles corresponding to all windows currently open  Wait for the popup to appear before calling this method! 74
  • 75. Handling popup windows (contd.)  By default, WebDriver “sees” UI elements on the main page only; use the “driver.switchTo().window()” API along with the corresponding window handle to point WebDriver at popup windows other than the main page  WebDriver also allows you to switch using the window name instead of the window handle:  The window name is specified by the developer of the web page –> use your browser dev tools to look for the window name  The window name is specified as one of the inputs (the 2nd one) to the JavaScript “window.open()” method – this function is typically called within the “onClick” event of the UI element which causes the popup to appear 75
  • 76. Handling frames (~15 mins)  A frame is an isolated section within a web page, with the ability to load content independent of other frames on the same page  Frames are implemented using the <frame> or <iframe> tags within HTML  WebDriver treats frames just like any other UI element -> Use “driver.findElement()” along with a suitable locator to identify a frame object  By default, WebDriver “sees” UI elements on the main page only; use the “driver.switchTo().frame()” API along with the frame identified as a “WebElement” to point WebDriver at specific frames within the main page 76
  • 77. Executing multiple tests in parallel (~30 mins)  WebDriver is probably the only automation tool that supports execution of multiple tests in parallel (on a single machine):  Parallel execution works even while using different browsers together  Screenshots get captured just fine, even while running tests in parallel!  Tests can be executed in parallel using Java multi-threaded programming  Option 1: Use Java thread pools to run your tests  Option 2: Use TestNG’s in-built capabilities for multi-threaded execution 77
  • 78. Executing multiple tests in parallel (contd.)  Things to remember:  WebDriver is NOT thread-safe:  This means that a single driver instance cannot be shared across multiple threads -> WebDriver is deliberately designed this way  Use techniques such as “ThreadLocal” to ensure that each thread has its own ISOLATED WebDriver instance  Be wary of using static fields within your tests -> Remember that static fields are shared across all threads:  If a static field is updated by one thread, all other threads will see the updated value. This could cause unexpected results unless handled carefully.  Gotchas while using IE:  The IE Driver may require the browser to be in focus during execution  This could cause problems while running tests in parallel on IE and another browser 78
  • 79. Miscellaneous topics (~15 mins)  Taking screenshots during script execution:  Cast the WebDriver object to a “TakesScreenshot” object  Use the “getScreenshotAs()” API, in conjunction with a suitable output type  The most common output type is a file  Advanced user interactions – The Actions API:  Mouse interactions -> The moveToElement() (mouse overs), dragAndDrop(), doubleClick() API’s  Keyboard interactions -> The keyDown(), keyUp() API’s 79
  • 80. Sample exercises  Automate a sample workflow on any application, and apply the following concepts:  Synchronization  Screenshots  Frame and popup window handling  Run the workflow that you automated on 2 or more browsers in parallel 80
  • 82. In this chapter…  A peek inside the WebDriver architecture  Working with RemoteWebDriver  A deep-dive into Selenium Grid 82
  • 83. A peek inside the WebDriver architecture (~15 mins) 83 WebDriver Interface GeckoDriver ChromeDriver EdgeDriver InternetExplorerDriver chromedriver.exe IEDriverServer.exe Chrome browser IE browser Firefox browser Test script SafariDriver OperaDriver GhostDriver RemoteWebDriver AppiumDriver geckodriver.exe operadriver.exe phantomjs.exe <Selenium server> Any remote browser PhantomJS browser Opera browser Safari browser <Appium server> Mobile devices Edge browserMicrosoftWebDriver.exe <Embedded driver within Safari browser> <Browser driver.exe> Client side Server side HTTP Request / Response
  • 84. A peek inside the WebDriver architecture (contd.)  Client server based architecture, http based communication  Test scripts represent the client side; the individual browser drivers represent the server side  Servers are auto-started and auto-stopped by clients:  Glitches in test code may sometimes prevent servers from shutting down properly - > these remain persistent in memory and need to be manually killed  Each programming language supported by WebDriver is in effect a separate implementation of the client side 84
  • 85. A peek inside the WebDriver architecture (contd.)  On the other hand, the server side needs only 1 implementation, and can be built on any technology as desired by the respective browser manufacturers  RemoteWebDriver is a special implementation of WebDriver, which enables the client and server to exist on different machines within the same network  It is built using Java  Note that the server as well as the client are bundled into the same “selenium- standalone-server.jar” file!  Appium is another special implementation of WebDriver, which enables test scripts to be executed on mobile devices  It is built using Node.js 85
  • 86. A peek inside the WebDriver architecture (contd.)  Going forward into Selenium 3.0, release cycles will be decoupled for the client and server sides:  Server side releases will typically be synchronized with the individual browser release cycles, and will be more frequent  Client side releases will relate to new capabilities getting added to WebDriver, and will be relatively less frequent 86
  • 87. Working with RemoteWebDriver (~30 mins)  Starting the server on the remote machine:  Start the selenium server by running the Selenium standalone JAR file from the command line:  java –jar “selenium-standalone-server-3.0.1.jar”  The server starts on port 4444 by default. You can change it using the “-port” switch  java –jar “selenium-standalone-server-3.0.1.jar” –port 6789  Specify the location of browser driver exe files by using the “-D” switch along with the name of the system property to be set:  java –Dwebdriver.chrome.driver=“C:webdriverchromedriver.exe” –jar “selenium- standalone-server-3.0.1.jar”  View the server console:  Use the URL: http://server:port/wd/hub/static/resource/hub.html 87
  • 88. Working with RemoteWebDriver (contd.)  Pointing your script (client) to the server:  Instantiate a “RemoteWebDriver” object using the new keyword  Specify the remote server URL while instantiating the RemoteWebDriver:  Use the URL: http://server:port/wd/hub  Specify server side expectations using the “DesiredCapabilities” API  Browser, browser version, platform, etc. to be used on the remote machine  Remember to properly close out all sessions using the quit() API!  Sample exercise:  Execute any of your scripts on a remote machine -> work in pairs and run on each other’s machine 88
  • 89. A deep-dive into Selenium Grid (~60 mins)  What is Selenium Grid?  A mechanism to scale test execution by distributing it across multiple machines  An extension of the RemoteWebDriver, in which the selenium server plays special roles known as “hub” and “node”  How does the grid work?  Hub:  Centralized controller for the grid  One stop destination for all test scripts  Delegates test execution to connected nodes based on availability  Does not participate directly towards test execution 89
  • 90. A deep-dive into Selenium Grid (contd.)  How does the grid work (contd.)?  Node(s):  Individual server instances managed by the hub  A single node can handle multiple instances of multiple browsers in parallel, depending on how it is configured  E.g.: 5 instances of Chrome and 5 instances of Firefox  It is possible to run multiple nodes on the same machine, by using different ports  It is possible to run a hub and a node together on the same machine! 90
  • 91. A deep-dive into Selenium Grid (contd.)  Setting up the grid:  Starting the hub and node(s):  Run selenium server from the command line  Use the “-role” switch to indicate whether the server needs to run as a hub or as a node  If the server is running under the role of a node, you need to “register” it to the central hub using the “-hub” switch 91
  • 92. A deep-dive into Selenium Grid (contd.)  Setting up the grid (contd.):  Configuring the capabilities of a given node:  Every grid node automatically detects all browsers installed on the machine and configures itself as appropriate  This can be overridden manually using one of the following methods:  Using various switches directly on the command line  Using the “-nodeConfig” flag to read the capabilities from a JSON configuration file  Configure the “maxInstances” flag depending on the number of parallel instances the node machine can handle without running out of memory or crashing:  Remember that IE has issues with parallel execution; this means that you should ideally set “maxInstances” to 1 whenever you setup an IE node, and avoid using the node with any other browsers in parallel 92
  • 93. A deep-dive into Selenium Grid (contd.)  Setting up the grid (contd.):  Viewing the Grid console:  Access via the browser @ http://hub-server:port/grid/console  The console displays the list of nodes being managed by the hub, along with their respective capabilities 93
  • 94. A deep-dive into Selenium Grid (contd.)  Running scripts against the grid:  Use the DesiredCapabilities and RemoteWebDriver APIs  Specify the hub’s URL while instantiating the RemoteWebDriver  Achieve parallelism using Java thread pools or TestNG as explained in the previous session  Cloud based grid solutions:  Sauce Labs  BrowserStack  SmartBear CrossBrowserTesting 94
  • 95. Sample exercises  Setup a Selenium Grid  Work in groups of 3 or 4  Execute your scripts on the Grid  Optional: Sign up for a trial on Sauce Labs and execute your scripts against the cloud 95
  • 96. Module recap In this module, you learnt:  Special considerations while using WebDriver  A peek inside the WebDriver architecture  Working with RemoteWebDriver  A deep-dive into Selenium Grid Congratulations, you have completed the Selenium Expert module! 96
  • 97. THANK YOU! Vijay Ramaswamy Test Architect & Consultant 97