SlideShare a Scribd company logo
1 of 70
Testing Java Web Applications with
Selenium: A Cookbook
JavaOne 2016 – CON3080
Jorge Hidalgo & Vicente González
Presenter Introductions
Shameless Marketing Division
Copyright © 2016 Accenture All rights reserved. 2
Presenter Introductions
Copyright © 2016 Accenture All rights reserved. 3
Jorge Hidalgo
@_deors
deors
Senior Technology Architect
Global Java Community Lead
Accenture Spain
Father of two children, husband, irish flute &
whistle player, video gamer, master chief
apprentice, sci-fi ‘junkie’, Star Wars fan,
eternal Lego journeyman, gadget lover and
in love with Raspberry Pi computers
Vicente González
@viarellano
viarellano
Technology Architect
Global Java Community Champion
Accenture Spain
52 month experience husband, proud father
of 2 years old princess Regina, senior beach
user, cooking lover, associate padel player,
master Feria de Abril enthusiast, Sevilla FC fan
and Pearl Jam ninja evangelizer
Selenium
What is Selenium?
Copyright © 2016 Accenture All rights reserved. 4
Selenium
• Selenium is a web browser automation tool
• Automate any kind of interaction with a web application
• Script to create 1,000 users from data in a spreadsheet
• Script to download all invoices in a monthly basis
• Automate functional test scripts!
• No backdoor tricks, as close to the real stuff as possible
• Excellent for functional test script automation
Copyright © 2016 Accenture All rights reserved. 5
Selenium
• Selenium is open source
• No vendor lock-in
• Smaller inversion (in both capital and operational expenses)
• Selenium is mature and with a large and vibrant community
• Runs in many browsers and systems
• Scripts can be written in many programming languages
• Selenium usage is widely extended
• Easier to find people with the skill
Copyright © 2016 Accenture All rights reserved. 6
Selenium
• Selenium is formed of various components/projects:
• Selenium WebDriver
• Core API and language bindings – to interact with browsers
• Browser-specific implementations – because they are not created equal
• Executes scripts (tests) in local and remote machines
• Selenium Grid
• Simple, efficient, client-server setup to distribute test execution and workload
• Across many machines, multiple operating systems and browsers
• Even mobile OS/browsers
• Selenium IDE
• Firefox plug-in to record and playback tests
Copyright © 2016 Accenture All rights reserved. 7
Demo #1
• Selenium in one minute... maybe in two
Copyright © 2016 Accenture All rights reserved. 8
Selenium 101
• Writing a test script is simple using the WebDriver API
• Very much resembles what the tester is doing
• Scripts are usually wrapped in a test framework like JUnit
• Assertion capabilities
• Reporting capabilities
WebDriver driver = new ChromeDriver();
WebElement findOwnerLink = driver.findElement(By.linkText("Find owner"));
findOwnerLink.click();
driver.findElement(By.id("lastName")).sendKeys("Schroeder");
driver.findElement(By.id("findowners")).click();
Copyright © 2016 Accenture All rights reserved. 9
Selenium 101
• The WebDriver API has methods to:
• Find elements in a page:
• By its ID (the preferred way)
• By the text in a link, CSS selector, class name, element name
• Interact with the elements:
• Click a button
• Enter text in (or clear) a text field
• Select a value in a radio-button or drop-down list
• Access to the page source:
• For example, to verify if some JavaScript or some arbitrary text is present
• Take screenshots!
Copyright © 2016 Accenture All rights reserved. 10
Selenium 101
• It is even possible to work with DOM using XPath expressions
Copyright © 2016 Accenture All rights reserved. 11
Tip #1
Working with the DOM in Selenium
Copyright © 2016 Accenture All rights reserved. 12
Tip #1 – Working with the DOM
• The first rule of working with the DOM in Selenium is...
Copyright © 2016 Accenture All rights reserved. 13
Tip #1 – Working with the DOM
• The first rule of working with the DOM in Selenium is...
• ...WE DON’T WORK WITH THE DOM IN SELENIUM!
Copyright © 2016 Accenture All rights reserved. 14
Tip #1 – Working with the DOM
• We are *very* serious
• Working directly with the DOM makes tests brittle
• They focus on the implementation detail
• They move far from the perspective of the tester
• Interact with visual, recognizable, elements in the UI
• Test cases are hard to maintain and easy to break
• Use this option only as a last resort mechanism
• And when doing it, document the tests so it is easier to understand
what it pretends
Copyright © 2016 Accenture All rights reserved. 15
Tip #1 – Working with the DOM
• As a corollary, two derived tips – these two come from conversations
with developers arguing about ‘why we don’t automate our tests’
• Tip #1.1
• “Our web pages don’t have IDs”
• Always add meaningful IDs in generated / crafted HTML elements
• If possible, make them unique (or at least grouped by function)
• Tip #1.2
• “The framework we are using generate random or non-consistent IDs”
• Pick another framework! 
• Testability must be a primary driver while taking technology decisions
Copyright © 2016 Accenture All rights reserved. 16
Running Selenium
• Step 1)
• Start the Selenium grid
• Step 2)
• Start the application to be tested
• Step 3)
• Launch the tests
Copyright © 2016 Accenture All rights reserved. 17
Running Selenium
• Step 1)
• Start the Selenium grid
• Add the Selenium folder to PATH – external drivers need to be found at runtime
• Add the Selenium folder to PATH – external drivers need to be found at runtime
• Then each of the test nodes
set PATH=%PATH%;%SELENIUM_HOME% or export PATH=$PATH:$SELENIUM_HOME
java -jar selenium-server-standalone-2.53.1.jar -role node -port 5555 
-hub http://localhost:4444/grid/register 
-browser browserName=chrome 
-browser browserName=firefox
java -jar selenium-server-standalone-2.53.1.jar -role hub -port 4444
Copyright © 2016 Accenture All rights reserved. 18
Running Selenium
• Step 2)
• Start the application to be tested
• In your local IDE
• A local or remote server (command-line, script, service...)
• In a continuous integration job
• Step 3)
• Launch the tests
• In your local IDE
• A local or remote process (command-line, script...)
• In a continuous integration job
Copyright © 2016 Accenture All rights reserved. 19
Demo #1 revisited
• Let’s repeat the demo following the process step by step
Copyright © 2016 Accenture All rights reserved. 20
Tip #2
Automate Test Data Creation
Copyright © 2016 Accenture All rights reserved. 21
Tip #2 – Test Data Creation
• Start by crafting scripts to create test data
• Very simple scripts
• Use input files (CSV, spreadsheet) to provide data for multiple records
• Even if nothing else is automated, there is business value in those
scripts
• These scripts are very easy to transform in a functional test script
• Add some assertions on the output (ok/error)
• Use DbUnit to assert the state in the database is the expected one
Copyright © 2016 Accenture All rights reserved. 22
Tip #2 – Test Data Creation
• Using Pet Clinic as a example, let’s create a few owners. Start by
reading the file and feed the test data to the script
private Optional<Owner> parseOwner(String testDataLine) {
String[] testDataTokens = testDataLine.split("t");
if (testDataTokens.length != 5) {
return Optional.empty();
} else {
Owner owner = new Owner();
owner.setFirstName(testDataTokens[0]);
owner.setLastName(testDataTokens[1]);
owner.setAddress(testDataTokens[2]);
owner.setCity(testDataTokens[3]);
owner.setTelephone(testDataTokens[4]);
return Optional.of(owner);
}
}
Copyright © 2016 Accenture All rights reserved. 23
Tip #2 – Test Data Creation
• For each line in the file, a new owner will be created. To keep things
clean, let’s separate test data logic from the actual test steps
private void createNewUserBulk(final WebDriver driver, final String baseUrl) {
Optional<List<String>> testData = readTestData();
if (testData.isPresent()) {
for (String testDataLine : testData.get()) {
Optional<Owner> owner = parseOwner(testDataLine);
if (owner.isPresent()) {
createNewUser(driver, baseUrl, owner.get());
}
}
}
}
Copyright © 2016 Accenture All rights reserved. 24
Tip #2 – Test Data Creation
• The actual test steps are very, very simple – just access the form,
populate the data, and click the button
private void createNewUser(
final WebDriver driver, final String baseUrl, Owner owner) {
driver.get(baseUrl + "/owners/new");
driver.findElement(By.id("firstName")).sendKeys(owner.getFirstName());
driver.findElement(By.id("lastName")).sendKeys(owner.getLastName());
driver.findElement(By.id("address")).sendKeys(owner.getAddress());
driver.findElement(By.id("city")).sendKeys(owner.getCity());
driver.findElement(By.id("telephone")).sendKeys(owner.getTelephone());
driver.findElement(By.id("addowner")).click();
}
Copyright © 2016 Accenture All rights reserved. 25
Tip #2 – Test Data Creation
• Adding assertions is simple and will transform the useful test data
creation script into a functional test case (even more useful)
private void createNewUser(
final WebDriver driver, final String baseUrl, Owner owner) {
...
driver.findElement(By.id("addowner")).click();
assertTrue(driver.getPageSource().contains(owner.getFirstName()));
assertTrue(driver.getPageSource().contains(owner.getLastName()));
assertTrue(driver.getPageSource().contains(owner.getAddress()));
assertTrue(driver.getPageSource().contains(owner.getCity()));
assertTrue(driver.getPageSource().contains(owner.getTelephone()));
}
Copyright © 2016 Accenture All rights reserved. 26
Demo #2
• How to create multiple owners for the Pet Clinic application
Copyright © 2016 Accenture All rights reserved. 27
Tip #3
Decouple driver/browser logic from test logic
Copyright © 2016 Accenture All rights reserved. 28
Tip #3 – Decouple Driver/Browser Logic
• This will make tests reusable across browsers
• The election of which browsers will be used can be done externally
and passed as parameter to the test
• Using environment variables
• Using Java VM system properties
• Will work in 99% of test cases
• WebDriver API already decouples core from browser implementations
• In some corner cases, driver specific API idiom will be needed
Copyright © 2016 Accenture All rights reserved. 29
Tip #3 – Decouple Driver/Browser Logic
• An exemplar implementation in Jorge’s post here:
• Four steps:
• Step 1) Define some variables to hold desired setup
• Step 2) Read values from environment variables and/or system properties
• Step 3) Create test methods per browser and execute/skip test logic based on
the desired setup
• Step 4) Create test logic methods that receive a Driver and URL as parameters
https://deors.wordpress.com/2013/02/18/selectable-selenium/
Copyright © 2016 Accenture All rights reserved. 30
Tip #3 – Decouple Driver/Browser Logic
• Step 1) Define some variables to hold desired setup
private static boolean RUN_HTMLUNIT;
private static boolean RUN_FIREFOX;
private static boolean RUN_CHROME;
private static boolean RUN_OPERA;
private static boolean RUN_IE;
private static String SELENIUM_HUB_URL;
private static String TARGET_SERVER_URL;
Copyright © 2016 Accenture All rights reserved. 31
Tip #3 – Decouple Driver/Browser Logic
• Step 2) Read values from environment variables and/or system
properties (in a method annotated with @BeforeClass)
RUN_HTMLUNIT = getConfigurationProperty(
"RUN_HTMLUNIT",
"test.run.htmlunit",
true);
logger.info("running the tests in HtmlUnit: " + RUN_HTMLUNIT);
TARGET_SERVER_URL = getConfigurationProperty(
"TARGET_SERVER_URL",
"test.target.server.url",
"http://localhost:58080/petclinic");
logger.info("using target server at: " + TARGET_SERVER_URL);
Copyright © 2016 Accenture All rights reserved. 32
Tip #3 – Decouple Driver/Browser Logic
• More on Step 2) All properties should have sensible defaults. For
example:
• HtmlUnit browser, which is an in-memory browser, enabled by default
• All other browsers, which may or may not be present, disabled by default
• Selenium grid, running on localhost by default
• Application to be tested, running on localhost by default
• The default settings proposed above allows for easy test execution,
without further concern, in a developer workstation
Copyright © 2016 Accenture All rights reserved. 33
Tip #3 – Decouple Driver/Browser Logic
• Step 3) Create test methods (annotated with @Test) per browser and
execute/skip test logic based on the desired setup
@Test
public void testChrome() throws MalformedURLException, IOException {
Assume.assumeTrue(RUN_CHROME);
try {
Capabilities browser = DesiredCapabilities.chrome();
WebDriver driver = new RemoteWebDriver(new URL(SELENIUM_HUB_URL), browser);
testNewPetFirstVisit(driver, TARGET_SERVER_URL);
} finally {
if (driver != null) {
driver.quit();
}
}
}
Copyright © 2016 Accenture All rights reserved. 34
Tip #3 – Decouple Driver/Browser Logic
• Step 4) Create test logic methods (not annotated) that receive a
Driver and the base URL where the app is deployed as parameters
public void testNewPetFirstVisit(final WebDriver driver, final String baseUrl) {
driver.get(baseUrl);
WebElement findOwnerLink = driver.findElement(By.linkText("Find owner"));
findOwnerLink.click();
driver.findElement(By.id("lastName")).clear();
driver.findElement(By.id("lastName")).sendKeys("Schroeder");
driver.findElement(By.id("findowners")).click();
...
}
Copyright © 2016 Accenture All rights reserved. 35
Running Selenium (revisited)
When the tests are executed, parameters will be read, if any. If not,
sensible defaults will be applied, and tests executed.
Some examples:
• Run the tests in HtmlUnit, Chrome and Firefox, with Selenium grid and
application both deployed at localhost
• Run the tests in Chrome only, with Selenium grid and application deployed at
some remote (shared) servers
-Dtest.run.chrome=true -Dtest.run.firefox=true
-Dtest.run.htmlunit=false -Dtest.run.chrome=true 
-Dtest.selenium.hub.url=http://selenium.test.acme.com:4444/wd/hub 
-Dtest.target.server.url=http://appserver.test.acme.com:58080/petclinic
Copyright © 2016 Accenture All rights reserved. 36
Running Selenium (revisited)
If using Apache Maven, Failsafe plug-in should be used for integration
tests instead of Surefire (which should be used only for unit tests)
• Easy separation of unit test and integration test results
• Great if used along a code coverage tool like JaCoCo and a quality dashboard
like SonarQube
• Remember to pass test parameters embedded in argLine parameter so they
are passed appropriately to the JUnit test class:
mvn failsafe-integration-test -DargLine=" 
-Dtest.run.htmlunit=false -Dtest.run.chrome=true 
-Dtest.selenium.hub.url=http://selenium.test.acme.com:4444/wd/hub 
-Dtest.target.server.url=http://appserver.test.acme.com:58080/petclinic"
Copyright © 2016 Accenture All rights reserved. 37
Running Selenium (revisited)
This is an example of a continuous delivery pipeline in Jenkins which is
using separate build jobs for unit and integration tests
Internally it is using both Maven Surefire and Failsafe to differentiate
both suite executions
Test results can be used as a quality gate along the pipeline
Copyright © 2016 Accenture All rights reserved. 38
39Copyright © 2016 Accenture All rights reserved.
YOU SHALL NOT PASS!
Image © New Line Cinema: “The Lord of the Rings – The Fellowship of the Ring”
Running Selenium (revisited)
This is an example of how
using both Maven Surefire
and Failsafe allows for better
reporting
Tools, like SonarQube, which
are aware of the difference
between unit and integration
tests, can show coverage
metrics per kind of test, and
combine all for overall value
Copyright © 2016 Accenture All rights reserved. 40
Demo #3
• Working with multiple browsers from the IDE
• Role of Selenium in continuous delivery pipelines
Copyright © 2016 Accenture All rights reserved. 41
Tip #4
Use Wait conditions for quicker and more robust tests
Copyright © 2016 Accenture All rights reserved. 42
Tip #4 – Fluent Wait Conditions
• When at some point of the test, it is needed to wait for something to
happen
• Navigating to a new page
• Waiting for the server-side transaction to finish
• Waiting for an AJAX call
• Don’t be tempted by the dark side  – never use Thread.sleep() or
similar idiom
• If child process finishes sooner, time is wasted – scripts run slower
• WebDriver API provides with a more elegant approach –
WebDriverWait
Copyright © 2016 Accenture All rights reserved. 43
Copyright © 2016 Accenture All rights reserved. 44Image credit: http://imgur.com/gallery/x9IkCWC
Tip #4 – Fluent Wait Conditions
• WebDriverWait instances are created for a specific WebDriver
instance, good if multiple tests are executed in parallel
• The condition is passed as a Function or Predicate from Google Guava
(pre-Java 8 functional interfaces) so they are lambda-ready!
• The Function will evaluate some condition, for example find some
element and return it, or check that page title is as expected
• If the element is not found, the WebDriver API usual
NotFoundException is ignored until the timeout is over
Copyright © 2016 Accenture All rights reserved. 45
Tip #4 – Fluent Wait Conditions
• This is an example using pre-lambda syntax
driver.get(baseUrl);
// wait for the application to get fully loaded
WebElement findOwnerLink = (new WebDriverWait(driver, 5)).until(
new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver d) {
return d.findElement(By.linkText("Find owner"));
}
});
findOwnerLink.click();
...rest of script
Copyright © 2016 Accenture All rights reserved. 46
Tip #4 – Fluent Wait Conditions
• This is the very same example but using a lambda expression
• The cast is needed so the compiler knows which functional interface
is being used (Function or Predicate) as until() method is overloaded
driver.get(baseUrl);
// wait for the application to get fully loaded
WebElement findOwnerLink = (new WebDriverWait(driver, 5)).until(
(Function<WebDriver, WebElement>) d -> d.findElement(By.linkText("Find owner")));
findOwnerLink.click();
...rest of script
Copyright © 2016 Accenture All rights reserved. 47
Tip #4 – Fluent Wait Conditions
• This is another example using a Predicate as a lambda expression
• The cast is, once again, needed
...rest of script
findOwnerLink.click();
(new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d
-> d.getCurrentUrl().startsWith(baseUrl + "/owners/search"));
...rest of script
Copyright © 2016 Accenture All rights reserved. 48
Demo #4
• Focus on WebDriver fluent wait conditions
Copyright © 2016 Accenture All rights reserved. 49
Tip #5
Page Object idiom for highly reusable test scripts
Copyright © 2016 Accenture All rights reserved. 50
Tip #5 – Page Object Idiom
• Testing is about sending data, and verifying responses
• A test script should only contain details about data and operations,
and code to check the responses
• Implement an unique way for accessing each element in your page
• Decouple test code from the way you access elements from the UI
• Avoid reworking effort when your application changes
• Reduce duplicated code
Copyright © 2016 Accenture All rights reserved. 51
Tip #5 – Page Object Idiom
Page Object Pattern
• An abstraction of the web pages under test
• Encapsulates the code to access the web elements of the UI
• Provides an API that facilitates the creation of test cases even for
people who may not understand about the implementation
• Single point for rework
• Will make your test code more readable
Copyright © 2016 Accenture All rights reserved. 52
Tip #5 – Page Object Idiom
• Implement a constructor with the driver and the baseURL as the
parameter
public OwnerPage(WebDriver driver, String baseUrl) {
this.driver = driver;
this.baseUrl = baseUrl;
}
Copyright © 2016 Accenture All rights reserved. 53
Tip #5 – Page Object Idiom
• Define the elements in the page
private By titleElement = By.xpath("//h2");
private By mainContent = By.id("main");
private By editOwnerCommand = By.linkText("Edit Owner");
private By addNewPetCommand = By.linkText("Add New Pet");
private By editPetCommand = By.linkText("Edit Pet");
private By addVisitCommand = By.linkText("Add Visit");
private By linkToHome = By.linkText("Home");
private By nameTag = By.xpath("//table[1]/tbody/tr[1]/td"); //sorry about using the DOM this time...
private By addressTag = By.xpath("//table[1]/tbody/tr[2]/td"); //please don’t do this...
Copyright © 2016 Accenture All rights reserved. 54
Tip #5 – Page Object Idiom
• Provide the public API for accessing the elements in your page
public String getName() {
WebElement element = driver.findElement(nameTag);
String name = element.getText();
return name;
}
public String getAddress() {
WebElement element = driver.findElement(addressTag);
String address = element.getText();
return address;
}
Copyright © 2016 Accenture All rights reserved. 55
Tip #5 – Page Object Idiom
• …and for actions the user will do in the page under test
56Copyright © 2016 Accenture All rights reserved.
public PetPage navigateToEditPet(String petId) {
driver.findElement(editPetCommand).click();
(new WebDriverWait(driver, 5)).until(
(Predicate<WebDriver>) d
-> getUrl().startsWith(baseUrl + "/owners/"+petId+"/pets")
&& getUrl().contains("edit"));
return new PetPage(driver, baseUrl);
}
Tip #5 – Page Object Idiom
• The test code should be something like
driver.get(baseUrl);
HomePage homePage = new HomePage(driver, baseUrl);
FindOwnersPage findOwnersPage = homePage.navigateToFindOwners();
OwnerPage ownerPage = findOwnersPage.findOwner("Schroeder");
assertTrue(ownerPage.getName().contains("David Schroeder"));
PetPage petPage = ownerPage.navigateToAddNewPet();
petPage.createPet("Mimi", "2011-10-02");
assertTrue(ownerPage.getName().contains("David Schroeder"));
assertTrue(ownerPage.getMainText().contains("Mimi"));
assertTrue(ownerPage.getMainText().contains("2011-10-02"));
Copyright © 2016 Accenture All rights reserved. 57
Tip #5 – Page Object Idiom
• Before and after
driver.get(baseUrl);
HomePage homePage = new HomePage(driver, baseUrl);
FindOwnersPage findOwnersPage = homePage.navigateToFindOwners();
OwnerPage ownerPage = findOwnersPage.findOwner("Schroeder");
assertTrue(ownerPage.getName().contains("David Schroeder"));
driver.get(baseUrl);
WebElement findOwnerLink = (new WebDriverWait(driver, 5))
.until((Function<WebDriver, WebElement>) d
-> d.findElement(By.linkText("Find owner")));
findOwnerLink.click();
(new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d
-> d.getCurrentUrl().startsWith(baseUrl + "/owners/search"));
driver.findElement(By.id("lastName")).clear();
driver.findElement(By.id("lastName")).sendKeys("Schroeder");
driver.findElement(By.id("findowners")).click();
(new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d
-> d.getCurrentUrl().equals(baseUrl + "/owners/9"));
assertTrue(driver.findElement(By.id("main")).getText().contains("David Schroeder"));
Copyright © 2016 Accenture All rights reserved. 58
Demo #5
• Writing tests using Page Objects
Copyright © 2016 Accenture All rights reserved. 59
Tip #5+
Using the PageFactory with Page Object Design Pattern
Copyright © 2016 Accenture All rights reserved. 60
Tip #5+ – The PageFactory
• Use the PageFactory to initialize the elements of the page under test
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
...
public OwnerPageFactory(WebDriver driver, String baseUrl) {
this.driver = driver;
this.baseUrl = baseUrl;
PageFactory.initElements(driver, this);
}
Copyright © 2016 Accenture All rights reserved. 61
Tip #5+ – The PageFactory
• Use the FindBy annotation while defining the WebElements
@FindBy(id="main")
private WebElement mainContent;
@FindBy(linkText="Edit Owner")
private By editOwnerCommand;
@FindBy(linkText="Add New Pet")
private WebElement addNewPetCommand;
@FindBy(linkText="Edit Pet")
private WebElement editPetCommand;
@FindBy(linkText="Add Visit")
private WebElement addVisitCommand;
Copyright © 2016 Accenture All rights reserved. 62
Tip #5+ – The PageFactory
• Your test could be something like…
public PetPage navigateToEditPet(String petId) {
editPetCommand.click();
(new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d
-> getUrl().startsWith(baseUrl + "/owners/"+petId+"/pets")
&& getUrl().contains("edit"));
return new PetPage(driver, baseUrl);
}
Copyright © 2016 Accenture All rights reserved. 63
Demo #5+
• The Page Object design pattern and the PageFactory
Copyright © 2016 Accenture All rights reserved. 64
Tip #6
Working with Absolute Coordinates
Copyright © 2016 Accenture All rights reserved. 65
Tip #6 – Working with Absolute Coordinates
• As with Tip #1, this is a technique we do not recommend
• It makes tests brittle
• Element locations are likely to change in different browsers
• Even more difficult (and less useful) with responsive pages
• Only as a last resort mechanism
• In Selenium it is not directly possible to locate an element at some
point in page
• However, it is possible to traverse a list of elements, ask for each
element location and size, and identify whether an element is under
one specific point in page
Copyright © 2016 Accenture All rights reserved. 66
Tip #6 – Working with Absolute Coordinates
• To ask for location and size, use this WebDriver methods:
• For example:
WebElement.getLocation();
WebElement.getSize();
List<WebElement> elements = driver.findElements(By....);
for (WebElement e: elements) {
Point loc = e.getLocation();
Dimension size = e.getSize();
if (x >= loc.getX()
&& x <= loc.getX() + size.getWidth()
&& y >= loc.getY()
&& y <= loc.getY() + size.getHeight()) {
return e;
}
}
Copyright © 2016 Accenture All rights reserved. 67
Tip #6 – Working with Absolute Coordinates
• Having that multiple elements can be at the same physical location
• Exercise caution
• Do not traverse all page elements during a search
• Select carefully which elements to use: by class, tag name or XPath (DOM)
• For example, in Pet Clinic home, H2 and IMG elements overlap
Copyright © 2016 Accenture All rights reserved. 68
Demo #6
• Working with absolute coordinates
Copyright © 2016 Accenture All rights reserved. 69
Q & A
We wish you enjoyed the talk
Visit https://github.com/deors/deors.demos.petclinic to get the code
Copyright © 2016 Accenture All rights reserved. 70
Jorge Hidalgo
@_deors
Vicente González
@viarellano

More Related Content

What's hot

Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorialprad_123
 
Scaladays 2014 introduction to scalatest selenium dsl
Scaladays 2014   introduction to scalatest selenium dslScaladays 2014   introduction to scalatest selenium dsl
Scaladays 2014 introduction to scalatest selenium dslMatthew Farwell
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)Dave Haeffner
 
Q con shanghai2013-[黄舒泉]-[intel it openstack practice]
Q con shanghai2013-[黄舒泉]-[intel it openstack practice]Q con shanghai2013-[黄舒泉]-[intel it openstack practice]
Q con shanghai2013-[黄舒泉]-[intel it openstack practice]Michael Zhang
 
Drupal Deployment
Drupal DeploymentDrupal Deployment
Drupal DeploymentJeff Eaton
 
PowerShell Plus v4.7 Overview
PowerShell Plus v4.7 OverviewPowerShell Plus v4.7 Overview
PowerShell Plus v4.7 OverviewRichard Giles
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBMichal Bigos
 
Compliance Automation Workshop
Compliance Automation WorkshopCompliance Automation Workshop
Compliance Automation WorkshopChef
 
Introduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpecIntroduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpecNathen Harvey
 
PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!Thomas Lee
 
Effective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecNathen Harvey
 
Jenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated DeploymentJenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated DeploymentDan Stine
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - IntroductionAmr E. Mohamed
 
Managed Beans: When, Why and How
Managed Beans: When, Why and HowManaged Beans: When, Why and How
Managed Beans: When, Why and HowRussell Maher
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Julian Robichaux
 
Using Chef InSpec for Infrastructure Security
Using Chef InSpec for Infrastructure SecurityUsing Chef InSpec for Infrastructure Security
Using Chef InSpec for Infrastructure SecurityMandi Walls
 
Automating Compliance with InSpec - Chef Singapore Meetup
Automating Compliance with InSpec - Chef Singapore MeetupAutomating Compliance with InSpec - Chef Singapore Meetup
Automating Compliance with InSpec - Chef Singapore MeetupMatt Ray
 

What's hot (19)

Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorial
 
Scaladays 2014 introduction to scalatest selenium dsl
Scaladays 2014   introduction to scalatest selenium dslScaladays 2014   introduction to scalatest selenium dsl
Scaladays 2014 introduction to scalatest selenium dsl
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)
 
Q con shanghai2013-[黄舒泉]-[intel it openstack practice]
Q con shanghai2013-[黄舒泉]-[intel it openstack practice]Q con shanghai2013-[黄舒泉]-[intel it openstack practice]
Q con shanghai2013-[黄舒泉]-[intel it openstack practice]
 
Drupal Deployment
Drupal DeploymentDrupal Deployment
Drupal Deployment
 
PowerShell Plus v4.7 Overview
PowerShell Plus v4.7 OverviewPowerShell Plus v4.7 Overview
PowerShell Plus v4.7 Overview
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
 
Compliance Automation Workshop
Compliance Automation WorkshopCompliance Automation Workshop
Compliance Automation Workshop
 
Introduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpecIntroduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpec
 
PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!
 
Effective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpec
 
Jenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated DeploymentJenkins and Chef: Infrastructure CI and Automated Deployment
Jenkins and Chef: Infrastructure CI and Automated Deployment
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - Introduction
 
Managed Beans: When, Why and How
Managed Beans: When, Why and HowManaged Beans: When, Why and How
Managed Beans: When, Why and How
 
Powershell training material
Powershell training materialPowershell training material
Powershell training material
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
 
Using Chef InSpec for Infrastructure Security
Using Chef InSpec for Infrastructure SecurityUsing Chef InSpec for Infrastructure Security
Using Chef InSpec for Infrastructure Security
 
Just enough app server
Just enough app serverJust enough app server
Just enough app server
 
Automating Compliance with InSpec - Chef Singapore Meetup
Automating Compliance with InSpec - Chef Singapore MeetupAutomating Compliance with InSpec - Chef Singapore Meetup
Automating Compliance with InSpec - Chef Singapore Meetup
 

Viewers also liked

Selenium using Java
Selenium using JavaSelenium using Java
Selenium using JavaF K
 
Lessons Learned in Software Quality 1
Lessons Learned in Software Quality 1Lessons Learned in Software Quality 1
Lessons Learned in Software Quality 1Belal Raslan
 
Selenium Tips & Tricks
Selenium Tips & TricksSelenium Tips & Tricks
Selenium Tips & TricksDave Haeffner
 
Leading the Perfect Q&A in Any Presentation
Leading the Perfect Q&A in Any PresentationLeading the Perfect Q&A in Any Presentation
Leading the Perfect Q&A in Any PresentationSketchBubble
 
The Link Between Alcohol and Breast Cancer
The Link Between Alcohol and Breast CancerThe Link Between Alcohol and Breast Cancer
The Link Between Alcohol and Breast CancerDr. Omer Hameed
 

Viewers also liked (8)

Selenium using Java
Selenium using JavaSelenium using Java
Selenium using Java
 
Lessons Learned in Software Quality 1
Lessons Learned in Software Quality 1Lessons Learned in Software Quality 1
Lessons Learned in Software Quality 1
 
Selenium web driver in Java
Selenium web driver in JavaSelenium web driver in Java
Selenium web driver in Java
 
Foundation selenium java
Foundation selenium java Foundation selenium java
Foundation selenium java
 
Selenium Tips & Tricks
Selenium Tips & TricksSelenium Tips & Tricks
Selenium Tips & Tricks
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Leading the Perfect Q&A in Any Presentation
Leading the Perfect Q&A in Any PresentationLeading the Perfect Q&A in Any Presentation
Leading the Perfect Q&A in Any Presentation
 
The Link Between Alcohol and Breast Cancer
The Link Between Alcohol and Breast CancerThe Link Between Alcohol and Breast Cancer
The Link Between Alcohol and Breast Cancer
 

Similar to JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook

Selenium for everyone
Selenium for everyoneSelenium for everyone
Selenium for everyoneTft Us
 
TYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source Tools
TYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source ToolsTYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source Tools
TYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source ToolsMichael Lihs
 
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 | LearningSlotLearning Slot
 
Tools for Software Testing
Tools for Software TestingTools for Software Testing
Tools for Software TestingMohammed Moishin
 
Selenium- A Software Testing Tool
Selenium- A Software Testing ToolSelenium- A Software Testing Tool
Selenium- A Software Testing ToolZeba Tahseen
 
KrishnaToolComparisionPPT.pdf
KrishnaToolComparisionPPT.pdfKrishnaToolComparisionPPT.pdf
KrishnaToolComparisionPPT.pdfQA or the Highway
 
Test parallelization using Jenkins
Test parallelization using JenkinsTest parallelization using Jenkins
Test parallelization using JenkinsRogue Wave Software
 
Test automation using selenium
Test automation using seleniumTest automation using selenium
Test automation using seleniumTờ Rang
 
Build Fail-Proof Tests in Any Browser with Selenium
Build Fail-Proof Tests in Any Browser with SeleniumBuild Fail-Proof Tests in Any Browser with Selenium
Build Fail-Proof Tests in Any Browser with SeleniumTechWell
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfullyTEST Huddle
 
Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully Applitools
 
Selenium training
Selenium trainingSelenium training
Selenium trainingShivaraj R
 
Microsoft power point automation-opensourcetestingtools_matrix-1
Microsoft power point   automation-opensourcetestingtools_matrix-1Microsoft power point   automation-opensourcetestingtools_matrix-1
Microsoft power point automation-opensourcetestingtools_matrix-1tactqa
 
Microsoft power point automation-opensourcetestingtools_matrix-1
Microsoft power point   automation-opensourcetestingtools_matrix-1Microsoft power point   automation-opensourcetestingtools_matrix-1
Microsoft power point automation-opensourcetestingtools_matrix-1tactqa
 
Cloud Platforms for Java
Cloud Platforms for JavaCloud Platforms for Java
Cloud Platforms for Java3Pillar Global
 

Similar to JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook (20)

Selenium for everyone
Selenium for everyoneSelenium for everyone
Selenium for everyone
 
TYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source Tools
TYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source ToolsTYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source Tools
TYPO3 Camp Stuttgart 2015 - Continuous Delivery with Open Source Tools
 
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
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 
Selenium Training in Chennai
Selenium Training in ChennaiSelenium Training in Chennai
Selenium Training in Chennai
 
Selenium testing - Handle Elements in WebDriver
Selenium testing - Handle Elements in WebDriver Selenium testing - Handle Elements in WebDriver
Selenium testing - Handle Elements in WebDriver
 
Tools for Software Testing
Tools for Software TestingTools for Software Testing
Tools for Software Testing
 
Selenium- A Software Testing Tool
Selenium- A Software Testing ToolSelenium- A Software Testing Tool
Selenium- A Software Testing Tool
 
KrishnaToolComparisionPPT.pdf
KrishnaToolComparisionPPT.pdfKrishnaToolComparisionPPT.pdf
KrishnaToolComparisionPPT.pdf
 
Test parallelization using Jenkins
Test parallelization using JenkinsTest parallelization using Jenkins
Test parallelization using Jenkins
 
Automated ui-testing
Automated ui-testingAutomated ui-testing
Automated ui-testing
 
Test automation using selenium
Test automation using seleniumTest automation using selenium
Test automation using selenium
 
Build Fail-Proof Tests in Any Browser with Selenium
Build Fail-Proof Tests in Any Browser with SeleniumBuild Fail-Proof Tests in Any Browser with Selenium
Build Fail-Proof Tests in Any Browser with Selenium
 
Test automation proposal
Test automation proposalTest automation proposal
Test automation proposal
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfully
 
Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully
 
Selenium training
Selenium trainingSelenium training
Selenium training
 
Microsoft power point automation-opensourcetestingtools_matrix-1
Microsoft power point   automation-opensourcetestingtools_matrix-1Microsoft power point   automation-opensourcetestingtools_matrix-1
Microsoft power point automation-opensourcetestingtools_matrix-1
 
Microsoft power point automation-opensourcetestingtools_matrix-1
Microsoft power point   automation-opensourcetestingtools_matrix-1Microsoft power point   automation-opensourcetestingtools_matrix-1
Microsoft power point automation-opensourcetestingtools_matrix-1
 
Cloud Platforms for Java
Cloud Platforms for JavaCloud Platforms for Java
Cloud Platforms for Java
 

More from Jorge Hidalgo

GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22Jorge Hidalgo
 
GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18Jorge Hidalgo
 
Architecture 2020 - eComputing 2019-07-01
Architecture 2020 - eComputing 2019-07-01Architecture 2020 - eComputing 2019-07-01
Architecture 2020 - eComputing 2019-07-01Jorge Hidalgo
 
GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28Jorge Hidalgo
 
GraalVM - MálagaJUG 2018-11-29
GraalVM - MálagaJUG 2018-11-29GraalVM - MálagaJUG 2018-11-29
GraalVM - MálagaJUG 2018-11-29Jorge Hidalgo
 
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)Jorge Hidalgo
 
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...Jorge Hidalgo
 
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...Jorge Hidalgo
 
DevOps Te Cambia la Vida - eComputing 2018-07-03
DevOps Te Cambia la Vida - eComputing 2018-07-03DevOps Te Cambia la Vida - eComputing 2018-07-03
DevOps Te Cambia la Vida - eComputing 2018-07-03Jorge Hidalgo
 
Open Source Power Tools - Opensouthcode 2018-06-02
Open Source Power Tools - Opensouthcode 2018-06-02Open Source Power Tools - Opensouthcode 2018-06-02
Open Source Power Tools - Opensouthcode 2018-06-02Jorge Hidalgo
 
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...Jorge Hidalgo
 
JavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
JavaOne 2017 CON3276 - Selenium Testing Patterns ReloadedJavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
JavaOne 2017 CON3276 - Selenium Testing Patterns ReloadedJorge Hidalgo
 
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power ToolsJavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power ToolsJorge Hidalgo
 
All Your Faces Belong to Us - Opensouthcode 2017-05-06
All Your Faces Belong to Us - Opensouthcode 2017-05-06All Your Faces Belong to Us - Opensouthcode 2017-05-06
All Your Faces Belong to Us - Opensouthcode 2017-05-06Jorge Hidalgo
 
Por qué DevOps, por qué ahora @ CHAPI 2017
Por qué DevOps, por qué ahora @ CHAPI 2017Por qué DevOps, por qué ahora @ CHAPI 2017
Por qué DevOps, por qué ahora @ CHAPI 2017Jorge Hidalgo
 
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)Jorge Hidalgo
 
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17Jorge Hidalgo
 
OpenSlava 2016 - Lightweight Java Architectures
OpenSlava 2016 - Lightweight Java ArchitecturesOpenSlava 2016 - Lightweight Java Architectures
OpenSlava 2016 - Lightweight Java ArchitecturesJorge Hidalgo
 
OpenSouthCode 2016 - Accenture DevOps Platform 2016-05-07
OpenSouthCode 2016  - Accenture DevOps Platform 2016-05-07OpenSouthCode 2016  - Accenture DevOps Platform 2016-05-07
OpenSouthCode 2016 - Accenture DevOps Platform 2016-05-07Jorge Hidalgo
 
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost ComputersJavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost ComputersJorge Hidalgo
 

More from Jorge Hidalgo (20)

GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22
 
GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18
 
Architecture 2020 - eComputing 2019-07-01
Architecture 2020 - eComputing 2019-07-01Architecture 2020 - eComputing 2019-07-01
Architecture 2020 - eComputing 2019-07-01
 
GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28
 
GraalVM - MálagaJUG 2018-11-29
GraalVM - MálagaJUG 2018-11-29GraalVM - MálagaJUG 2018-11-29
GraalVM - MálagaJUG 2018-11-29
 
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
 
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
 
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
 
DevOps Te Cambia la Vida - eComputing 2018-07-03
DevOps Te Cambia la Vida - eComputing 2018-07-03DevOps Te Cambia la Vida - eComputing 2018-07-03
DevOps Te Cambia la Vida - eComputing 2018-07-03
 
Open Source Power Tools - Opensouthcode 2018-06-02
Open Source Power Tools - Opensouthcode 2018-06-02Open Source Power Tools - Opensouthcode 2018-06-02
Open Source Power Tools - Opensouthcode 2018-06-02
 
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
 
JavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
JavaOne 2017 CON3276 - Selenium Testing Patterns ReloadedJavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
JavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
 
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power ToolsJavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
 
All Your Faces Belong to Us - Opensouthcode 2017-05-06
All Your Faces Belong to Us - Opensouthcode 2017-05-06All Your Faces Belong to Us - Opensouthcode 2017-05-06
All Your Faces Belong to Us - Opensouthcode 2017-05-06
 
Por qué DevOps, por qué ahora @ CHAPI 2017
Por qué DevOps, por qué ahora @ CHAPI 2017Por qué DevOps, por qué ahora @ CHAPI 2017
Por qué DevOps, por qué ahora @ CHAPI 2017
 
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
 
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
 
OpenSlava 2016 - Lightweight Java Architectures
OpenSlava 2016 - Lightweight Java ArchitecturesOpenSlava 2016 - Lightweight Java Architectures
OpenSlava 2016 - Lightweight Java Architectures
 
OpenSouthCode 2016 - Accenture DevOps Platform 2016-05-07
OpenSouthCode 2016  - Accenture DevOps Platform 2016-05-07OpenSouthCode 2016  - Accenture DevOps Platform 2016-05-07
OpenSouthCode 2016 - Accenture DevOps Platform 2016-05-07
 
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost ComputersJavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
 

Recently uploaded

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 

Recently uploaded (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 

JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook

  • 1. Testing Java Web Applications with Selenium: A Cookbook JavaOne 2016 – CON3080 Jorge Hidalgo & Vicente González
  • 2. Presenter Introductions Shameless Marketing Division Copyright © 2016 Accenture All rights reserved. 2
  • 3. Presenter Introductions Copyright © 2016 Accenture All rights reserved. 3 Jorge Hidalgo @_deors deors Senior Technology Architect Global Java Community Lead Accenture Spain Father of two children, husband, irish flute & whistle player, video gamer, master chief apprentice, sci-fi ‘junkie’, Star Wars fan, eternal Lego journeyman, gadget lover and in love with Raspberry Pi computers Vicente González @viarellano viarellano Technology Architect Global Java Community Champion Accenture Spain 52 month experience husband, proud father of 2 years old princess Regina, senior beach user, cooking lover, associate padel player, master Feria de Abril enthusiast, Sevilla FC fan and Pearl Jam ninja evangelizer
  • 4. Selenium What is Selenium? Copyright © 2016 Accenture All rights reserved. 4
  • 5. Selenium • Selenium is a web browser automation tool • Automate any kind of interaction with a web application • Script to create 1,000 users from data in a spreadsheet • Script to download all invoices in a monthly basis • Automate functional test scripts! • No backdoor tricks, as close to the real stuff as possible • Excellent for functional test script automation Copyright © 2016 Accenture All rights reserved. 5
  • 6. Selenium • Selenium is open source • No vendor lock-in • Smaller inversion (in both capital and operational expenses) • Selenium is mature and with a large and vibrant community • Runs in many browsers and systems • Scripts can be written in many programming languages • Selenium usage is widely extended • Easier to find people with the skill Copyright © 2016 Accenture All rights reserved. 6
  • 7. Selenium • Selenium is formed of various components/projects: • Selenium WebDriver • Core API and language bindings – to interact with browsers • Browser-specific implementations – because they are not created equal • Executes scripts (tests) in local and remote machines • Selenium Grid • Simple, efficient, client-server setup to distribute test execution and workload • Across many machines, multiple operating systems and browsers • Even mobile OS/browsers • Selenium IDE • Firefox plug-in to record and playback tests Copyright © 2016 Accenture All rights reserved. 7
  • 8. Demo #1 • Selenium in one minute... maybe in two Copyright © 2016 Accenture All rights reserved. 8
  • 9. Selenium 101 • Writing a test script is simple using the WebDriver API • Very much resembles what the tester is doing • Scripts are usually wrapped in a test framework like JUnit • Assertion capabilities • Reporting capabilities WebDriver driver = new ChromeDriver(); WebElement findOwnerLink = driver.findElement(By.linkText("Find owner")); findOwnerLink.click(); driver.findElement(By.id("lastName")).sendKeys("Schroeder"); driver.findElement(By.id("findowners")).click(); Copyright © 2016 Accenture All rights reserved. 9
  • 10. Selenium 101 • The WebDriver API has methods to: • Find elements in a page: • By its ID (the preferred way) • By the text in a link, CSS selector, class name, element name • Interact with the elements: • Click a button • Enter text in (or clear) a text field • Select a value in a radio-button or drop-down list • Access to the page source: • For example, to verify if some JavaScript or some arbitrary text is present • Take screenshots! Copyright © 2016 Accenture All rights reserved. 10
  • 11. Selenium 101 • It is even possible to work with DOM using XPath expressions Copyright © 2016 Accenture All rights reserved. 11
  • 12. Tip #1 Working with the DOM in Selenium Copyright © 2016 Accenture All rights reserved. 12
  • 13. Tip #1 – Working with the DOM • The first rule of working with the DOM in Selenium is... Copyright © 2016 Accenture All rights reserved. 13
  • 14. Tip #1 – Working with the DOM • The first rule of working with the DOM in Selenium is... • ...WE DON’T WORK WITH THE DOM IN SELENIUM! Copyright © 2016 Accenture All rights reserved. 14
  • 15. Tip #1 – Working with the DOM • We are *very* serious • Working directly with the DOM makes tests brittle • They focus on the implementation detail • They move far from the perspective of the tester • Interact with visual, recognizable, elements in the UI • Test cases are hard to maintain and easy to break • Use this option only as a last resort mechanism • And when doing it, document the tests so it is easier to understand what it pretends Copyright © 2016 Accenture All rights reserved. 15
  • 16. Tip #1 – Working with the DOM • As a corollary, two derived tips – these two come from conversations with developers arguing about ‘why we don’t automate our tests’ • Tip #1.1 • “Our web pages don’t have IDs” • Always add meaningful IDs in generated / crafted HTML elements • If possible, make them unique (or at least grouped by function) • Tip #1.2 • “The framework we are using generate random or non-consistent IDs” • Pick another framework!  • Testability must be a primary driver while taking technology decisions Copyright © 2016 Accenture All rights reserved. 16
  • 17. Running Selenium • Step 1) • Start the Selenium grid • Step 2) • Start the application to be tested • Step 3) • Launch the tests Copyright © 2016 Accenture All rights reserved. 17
  • 18. Running Selenium • Step 1) • Start the Selenium grid • Add the Selenium folder to PATH – external drivers need to be found at runtime • Add the Selenium folder to PATH – external drivers need to be found at runtime • Then each of the test nodes set PATH=%PATH%;%SELENIUM_HOME% or export PATH=$PATH:$SELENIUM_HOME java -jar selenium-server-standalone-2.53.1.jar -role node -port 5555 -hub http://localhost:4444/grid/register -browser browserName=chrome -browser browserName=firefox java -jar selenium-server-standalone-2.53.1.jar -role hub -port 4444 Copyright © 2016 Accenture All rights reserved. 18
  • 19. Running Selenium • Step 2) • Start the application to be tested • In your local IDE • A local or remote server (command-line, script, service...) • In a continuous integration job • Step 3) • Launch the tests • In your local IDE • A local or remote process (command-line, script...) • In a continuous integration job Copyright © 2016 Accenture All rights reserved. 19
  • 20. Demo #1 revisited • Let’s repeat the demo following the process step by step Copyright © 2016 Accenture All rights reserved. 20
  • 21. Tip #2 Automate Test Data Creation Copyright © 2016 Accenture All rights reserved. 21
  • 22. Tip #2 – Test Data Creation • Start by crafting scripts to create test data • Very simple scripts • Use input files (CSV, spreadsheet) to provide data for multiple records • Even if nothing else is automated, there is business value in those scripts • These scripts are very easy to transform in a functional test script • Add some assertions on the output (ok/error) • Use DbUnit to assert the state in the database is the expected one Copyright © 2016 Accenture All rights reserved. 22
  • 23. Tip #2 – Test Data Creation • Using Pet Clinic as a example, let’s create a few owners. Start by reading the file and feed the test data to the script private Optional<Owner> parseOwner(String testDataLine) { String[] testDataTokens = testDataLine.split("t"); if (testDataTokens.length != 5) { return Optional.empty(); } else { Owner owner = new Owner(); owner.setFirstName(testDataTokens[0]); owner.setLastName(testDataTokens[1]); owner.setAddress(testDataTokens[2]); owner.setCity(testDataTokens[3]); owner.setTelephone(testDataTokens[4]); return Optional.of(owner); } } Copyright © 2016 Accenture All rights reserved. 23
  • 24. Tip #2 – Test Data Creation • For each line in the file, a new owner will be created. To keep things clean, let’s separate test data logic from the actual test steps private void createNewUserBulk(final WebDriver driver, final String baseUrl) { Optional<List<String>> testData = readTestData(); if (testData.isPresent()) { for (String testDataLine : testData.get()) { Optional<Owner> owner = parseOwner(testDataLine); if (owner.isPresent()) { createNewUser(driver, baseUrl, owner.get()); } } } } Copyright © 2016 Accenture All rights reserved. 24
  • 25. Tip #2 – Test Data Creation • The actual test steps are very, very simple – just access the form, populate the data, and click the button private void createNewUser( final WebDriver driver, final String baseUrl, Owner owner) { driver.get(baseUrl + "/owners/new"); driver.findElement(By.id("firstName")).sendKeys(owner.getFirstName()); driver.findElement(By.id("lastName")).sendKeys(owner.getLastName()); driver.findElement(By.id("address")).sendKeys(owner.getAddress()); driver.findElement(By.id("city")).sendKeys(owner.getCity()); driver.findElement(By.id("telephone")).sendKeys(owner.getTelephone()); driver.findElement(By.id("addowner")).click(); } Copyright © 2016 Accenture All rights reserved. 25
  • 26. Tip #2 – Test Data Creation • Adding assertions is simple and will transform the useful test data creation script into a functional test case (even more useful) private void createNewUser( final WebDriver driver, final String baseUrl, Owner owner) { ... driver.findElement(By.id("addowner")).click(); assertTrue(driver.getPageSource().contains(owner.getFirstName())); assertTrue(driver.getPageSource().contains(owner.getLastName())); assertTrue(driver.getPageSource().contains(owner.getAddress())); assertTrue(driver.getPageSource().contains(owner.getCity())); assertTrue(driver.getPageSource().contains(owner.getTelephone())); } Copyright © 2016 Accenture All rights reserved. 26
  • 27. Demo #2 • How to create multiple owners for the Pet Clinic application Copyright © 2016 Accenture All rights reserved. 27
  • 28. Tip #3 Decouple driver/browser logic from test logic Copyright © 2016 Accenture All rights reserved. 28
  • 29. Tip #3 – Decouple Driver/Browser Logic • This will make tests reusable across browsers • The election of which browsers will be used can be done externally and passed as parameter to the test • Using environment variables • Using Java VM system properties • Will work in 99% of test cases • WebDriver API already decouples core from browser implementations • In some corner cases, driver specific API idiom will be needed Copyright © 2016 Accenture All rights reserved. 29
  • 30. Tip #3 – Decouple Driver/Browser Logic • An exemplar implementation in Jorge’s post here: • Four steps: • Step 1) Define some variables to hold desired setup • Step 2) Read values from environment variables and/or system properties • Step 3) Create test methods per browser and execute/skip test logic based on the desired setup • Step 4) Create test logic methods that receive a Driver and URL as parameters https://deors.wordpress.com/2013/02/18/selectable-selenium/ Copyright © 2016 Accenture All rights reserved. 30
  • 31. Tip #3 – Decouple Driver/Browser Logic • Step 1) Define some variables to hold desired setup private static boolean RUN_HTMLUNIT; private static boolean RUN_FIREFOX; private static boolean RUN_CHROME; private static boolean RUN_OPERA; private static boolean RUN_IE; private static String SELENIUM_HUB_URL; private static String TARGET_SERVER_URL; Copyright © 2016 Accenture All rights reserved. 31
  • 32. Tip #3 – Decouple Driver/Browser Logic • Step 2) Read values from environment variables and/or system properties (in a method annotated with @BeforeClass) RUN_HTMLUNIT = getConfigurationProperty( "RUN_HTMLUNIT", "test.run.htmlunit", true); logger.info("running the tests in HtmlUnit: " + RUN_HTMLUNIT); TARGET_SERVER_URL = getConfigurationProperty( "TARGET_SERVER_URL", "test.target.server.url", "http://localhost:58080/petclinic"); logger.info("using target server at: " + TARGET_SERVER_URL); Copyright © 2016 Accenture All rights reserved. 32
  • 33. Tip #3 – Decouple Driver/Browser Logic • More on Step 2) All properties should have sensible defaults. For example: • HtmlUnit browser, which is an in-memory browser, enabled by default • All other browsers, which may or may not be present, disabled by default • Selenium grid, running on localhost by default • Application to be tested, running on localhost by default • The default settings proposed above allows for easy test execution, without further concern, in a developer workstation Copyright © 2016 Accenture All rights reserved. 33
  • 34. Tip #3 – Decouple Driver/Browser Logic • Step 3) Create test methods (annotated with @Test) per browser and execute/skip test logic based on the desired setup @Test public void testChrome() throws MalformedURLException, IOException { Assume.assumeTrue(RUN_CHROME); try { Capabilities browser = DesiredCapabilities.chrome(); WebDriver driver = new RemoteWebDriver(new URL(SELENIUM_HUB_URL), browser); testNewPetFirstVisit(driver, TARGET_SERVER_URL); } finally { if (driver != null) { driver.quit(); } } } Copyright © 2016 Accenture All rights reserved. 34
  • 35. Tip #3 – Decouple Driver/Browser Logic • Step 4) Create test logic methods (not annotated) that receive a Driver and the base URL where the app is deployed as parameters public void testNewPetFirstVisit(final WebDriver driver, final String baseUrl) { driver.get(baseUrl); WebElement findOwnerLink = driver.findElement(By.linkText("Find owner")); findOwnerLink.click(); driver.findElement(By.id("lastName")).clear(); driver.findElement(By.id("lastName")).sendKeys("Schroeder"); driver.findElement(By.id("findowners")).click(); ... } Copyright © 2016 Accenture All rights reserved. 35
  • 36. Running Selenium (revisited) When the tests are executed, parameters will be read, if any. If not, sensible defaults will be applied, and tests executed. Some examples: • Run the tests in HtmlUnit, Chrome and Firefox, with Selenium grid and application both deployed at localhost • Run the tests in Chrome only, with Selenium grid and application deployed at some remote (shared) servers -Dtest.run.chrome=true -Dtest.run.firefox=true -Dtest.run.htmlunit=false -Dtest.run.chrome=true -Dtest.selenium.hub.url=http://selenium.test.acme.com:4444/wd/hub -Dtest.target.server.url=http://appserver.test.acme.com:58080/petclinic Copyright © 2016 Accenture All rights reserved. 36
  • 37. Running Selenium (revisited) If using Apache Maven, Failsafe plug-in should be used for integration tests instead of Surefire (which should be used only for unit tests) • Easy separation of unit test and integration test results • Great if used along a code coverage tool like JaCoCo and a quality dashboard like SonarQube • Remember to pass test parameters embedded in argLine parameter so they are passed appropriately to the JUnit test class: mvn failsafe-integration-test -DargLine=" -Dtest.run.htmlunit=false -Dtest.run.chrome=true -Dtest.selenium.hub.url=http://selenium.test.acme.com:4444/wd/hub -Dtest.target.server.url=http://appserver.test.acme.com:58080/petclinic" Copyright © 2016 Accenture All rights reserved. 37
  • 38. Running Selenium (revisited) This is an example of a continuous delivery pipeline in Jenkins which is using separate build jobs for unit and integration tests Internally it is using both Maven Surefire and Failsafe to differentiate both suite executions Test results can be used as a quality gate along the pipeline Copyright © 2016 Accenture All rights reserved. 38
  • 39. 39Copyright © 2016 Accenture All rights reserved. YOU SHALL NOT PASS! Image © New Line Cinema: “The Lord of the Rings – The Fellowship of the Ring”
  • 40. Running Selenium (revisited) This is an example of how using both Maven Surefire and Failsafe allows for better reporting Tools, like SonarQube, which are aware of the difference between unit and integration tests, can show coverage metrics per kind of test, and combine all for overall value Copyright © 2016 Accenture All rights reserved. 40
  • 41. Demo #3 • Working with multiple browsers from the IDE • Role of Selenium in continuous delivery pipelines Copyright © 2016 Accenture All rights reserved. 41
  • 42. Tip #4 Use Wait conditions for quicker and more robust tests Copyright © 2016 Accenture All rights reserved. 42
  • 43. Tip #4 – Fluent Wait Conditions • When at some point of the test, it is needed to wait for something to happen • Navigating to a new page • Waiting for the server-side transaction to finish • Waiting for an AJAX call • Don’t be tempted by the dark side  – never use Thread.sleep() or similar idiom • If child process finishes sooner, time is wasted – scripts run slower • WebDriver API provides with a more elegant approach – WebDriverWait Copyright © 2016 Accenture All rights reserved. 43
  • 44. Copyright © 2016 Accenture All rights reserved. 44Image credit: http://imgur.com/gallery/x9IkCWC
  • 45. Tip #4 – Fluent Wait Conditions • WebDriverWait instances are created for a specific WebDriver instance, good if multiple tests are executed in parallel • The condition is passed as a Function or Predicate from Google Guava (pre-Java 8 functional interfaces) so they are lambda-ready! • The Function will evaluate some condition, for example find some element and return it, or check that page title is as expected • If the element is not found, the WebDriver API usual NotFoundException is ignored until the timeout is over Copyright © 2016 Accenture All rights reserved. 45
  • 46. Tip #4 – Fluent Wait Conditions • This is an example using pre-lambda syntax driver.get(baseUrl); // wait for the application to get fully loaded WebElement findOwnerLink = (new WebDriverWait(driver, 5)).until( new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver d) { return d.findElement(By.linkText("Find owner")); } }); findOwnerLink.click(); ...rest of script Copyright © 2016 Accenture All rights reserved. 46
  • 47. Tip #4 – Fluent Wait Conditions • This is the very same example but using a lambda expression • The cast is needed so the compiler knows which functional interface is being used (Function or Predicate) as until() method is overloaded driver.get(baseUrl); // wait for the application to get fully loaded WebElement findOwnerLink = (new WebDriverWait(driver, 5)).until( (Function<WebDriver, WebElement>) d -> d.findElement(By.linkText("Find owner"))); findOwnerLink.click(); ...rest of script Copyright © 2016 Accenture All rights reserved. 47
  • 48. Tip #4 – Fluent Wait Conditions • This is another example using a Predicate as a lambda expression • The cast is, once again, needed ...rest of script findOwnerLink.click(); (new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d -> d.getCurrentUrl().startsWith(baseUrl + "/owners/search")); ...rest of script Copyright © 2016 Accenture All rights reserved. 48
  • 49. Demo #4 • Focus on WebDriver fluent wait conditions Copyright © 2016 Accenture All rights reserved. 49
  • 50. Tip #5 Page Object idiom for highly reusable test scripts Copyright © 2016 Accenture All rights reserved. 50
  • 51. Tip #5 – Page Object Idiom • Testing is about sending data, and verifying responses • A test script should only contain details about data and operations, and code to check the responses • Implement an unique way for accessing each element in your page • Decouple test code from the way you access elements from the UI • Avoid reworking effort when your application changes • Reduce duplicated code Copyright © 2016 Accenture All rights reserved. 51
  • 52. Tip #5 – Page Object Idiom Page Object Pattern • An abstraction of the web pages under test • Encapsulates the code to access the web elements of the UI • Provides an API that facilitates the creation of test cases even for people who may not understand about the implementation • Single point for rework • Will make your test code more readable Copyright © 2016 Accenture All rights reserved. 52
  • 53. Tip #5 – Page Object Idiom • Implement a constructor with the driver and the baseURL as the parameter public OwnerPage(WebDriver driver, String baseUrl) { this.driver = driver; this.baseUrl = baseUrl; } Copyright © 2016 Accenture All rights reserved. 53
  • 54. Tip #5 – Page Object Idiom • Define the elements in the page private By titleElement = By.xpath("//h2"); private By mainContent = By.id("main"); private By editOwnerCommand = By.linkText("Edit Owner"); private By addNewPetCommand = By.linkText("Add New Pet"); private By editPetCommand = By.linkText("Edit Pet"); private By addVisitCommand = By.linkText("Add Visit"); private By linkToHome = By.linkText("Home"); private By nameTag = By.xpath("//table[1]/tbody/tr[1]/td"); //sorry about using the DOM this time... private By addressTag = By.xpath("//table[1]/tbody/tr[2]/td"); //please don’t do this... Copyright © 2016 Accenture All rights reserved. 54
  • 55. Tip #5 – Page Object Idiom • Provide the public API for accessing the elements in your page public String getName() { WebElement element = driver.findElement(nameTag); String name = element.getText(); return name; } public String getAddress() { WebElement element = driver.findElement(addressTag); String address = element.getText(); return address; } Copyright © 2016 Accenture All rights reserved. 55
  • 56. Tip #5 – Page Object Idiom • …and for actions the user will do in the page under test 56Copyright © 2016 Accenture All rights reserved. public PetPage navigateToEditPet(String petId) { driver.findElement(editPetCommand).click(); (new WebDriverWait(driver, 5)).until( (Predicate<WebDriver>) d -> getUrl().startsWith(baseUrl + "/owners/"+petId+"/pets") && getUrl().contains("edit")); return new PetPage(driver, baseUrl); }
  • 57. Tip #5 – Page Object Idiom • The test code should be something like driver.get(baseUrl); HomePage homePage = new HomePage(driver, baseUrl); FindOwnersPage findOwnersPage = homePage.navigateToFindOwners(); OwnerPage ownerPage = findOwnersPage.findOwner("Schroeder"); assertTrue(ownerPage.getName().contains("David Schroeder")); PetPage petPage = ownerPage.navigateToAddNewPet(); petPage.createPet("Mimi", "2011-10-02"); assertTrue(ownerPage.getName().contains("David Schroeder")); assertTrue(ownerPage.getMainText().contains("Mimi")); assertTrue(ownerPage.getMainText().contains("2011-10-02")); Copyright © 2016 Accenture All rights reserved. 57
  • 58. Tip #5 – Page Object Idiom • Before and after driver.get(baseUrl); HomePage homePage = new HomePage(driver, baseUrl); FindOwnersPage findOwnersPage = homePage.navigateToFindOwners(); OwnerPage ownerPage = findOwnersPage.findOwner("Schroeder"); assertTrue(ownerPage.getName().contains("David Schroeder")); driver.get(baseUrl); WebElement findOwnerLink = (new WebDriverWait(driver, 5)) .until((Function<WebDriver, WebElement>) d -> d.findElement(By.linkText("Find owner"))); findOwnerLink.click(); (new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d -> d.getCurrentUrl().startsWith(baseUrl + "/owners/search")); driver.findElement(By.id("lastName")).clear(); driver.findElement(By.id("lastName")).sendKeys("Schroeder"); driver.findElement(By.id("findowners")).click(); (new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d -> d.getCurrentUrl().equals(baseUrl + "/owners/9")); assertTrue(driver.findElement(By.id("main")).getText().contains("David Schroeder")); Copyright © 2016 Accenture All rights reserved. 58
  • 59. Demo #5 • Writing tests using Page Objects Copyright © 2016 Accenture All rights reserved. 59
  • 60. Tip #5+ Using the PageFactory with Page Object Design Pattern Copyright © 2016 Accenture All rights reserved. 60
  • 61. Tip #5+ – The PageFactory • Use the PageFactory to initialize the elements of the page under test import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.WebDriverWait; ... public OwnerPageFactory(WebDriver driver, String baseUrl) { this.driver = driver; this.baseUrl = baseUrl; PageFactory.initElements(driver, this); } Copyright © 2016 Accenture All rights reserved. 61
  • 62. Tip #5+ – The PageFactory • Use the FindBy annotation while defining the WebElements @FindBy(id="main") private WebElement mainContent; @FindBy(linkText="Edit Owner") private By editOwnerCommand; @FindBy(linkText="Add New Pet") private WebElement addNewPetCommand; @FindBy(linkText="Edit Pet") private WebElement editPetCommand; @FindBy(linkText="Add Visit") private WebElement addVisitCommand; Copyright © 2016 Accenture All rights reserved. 62
  • 63. Tip #5+ – The PageFactory • Your test could be something like… public PetPage navigateToEditPet(String petId) { editPetCommand.click(); (new WebDriverWait(driver, 5)).until((Predicate<WebDriver>) d -> getUrl().startsWith(baseUrl + "/owners/"+petId+"/pets") && getUrl().contains("edit")); return new PetPage(driver, baseUrl); } Copyright © 2016 Accenture All rights reserved. 63
  • 64. Demo #5+ • The Page Object design pattern and the PageFactory Copyright © 2016 Accenture All rights reserved. 64
  • 65. Tip #6 Working with Absolute Coordinates Copyright © 2016 Accenture All rights reserved. 65
  • 66. Tip #6 – Working with Absolute Coordinates • As with Tip #1, this is a technique we do not recommend • It makes tests brittle • Element locations are likely to change in different browsers • Even more difficult (and less useful) with responsive pages • Only as a last resort mechanism • In Selenium it is not directly possible to locate an element at some point in page • However, it is possible to traverse a list of elements, ask for each element location and size, and identify whether an element is under one specific point in page Copyright © 2016 Accenture All rights reserved. 66
  • 67. Tip #6 – Working with Absolute Coordinates • To ask for location and size, use this WebDriver methods: • For example: WebElement.getLocation(); WebElement.getSize(); List<WebElement> elements = driver.findElements(By....); for (WebElement e: elements) { Point loc = e.getLocation(); Dimension size = e.getSize(); if (x >= loc.getX() && x <= loc.getX() + size.getWidth() && y >= loc.getY() && y <= loc.getY() + size.getHeight()) { return e; } } Copyright © 2016 Accenture All rights reserved. 67
  • 68. Tip #6 – Working with Absolute Coordinates • Having that multiple elements can be at the same physical location • Exercise caution • Do not traverse all page elements during a search • Select carefully which elements to use: by class, tag name or XPath (DOM) • For example, in Pet Clinic home, H2 and IMG elements overlap Copyright © 2016 Accenture All rights reserved. 68
  • 69. Demo #6 • Working with absolute coordinates Copyright © 2016 Accenture All rights reserved. 69
  • 70. Q & A We wish you enjoyed the talk Visit https://github.com/deors/deors.demos.petclinic to get the code Copyright © 2016 Accenture All rights reserved. 70 Jorge Hidalgo @_deors Vicente González @viarellano