SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
!!
T9
Test!Automation!
10/16/2014!11:15:00!AM!
!
Automation Abstractions:
Page Objects and Beyond
!
Presented by:
Alan Richardson
Compendium Developments
!
!
!
Brought(to(you(by:(
(
(
(
340!Corporate!Way,!Suite!300,!Orange!Park,!FL!32073!
888G268G8770!H!904G278G0524!H!sqeinfo@sqe.com!H!www.sqe.com!
!
Alan Richardson
Compendium Developments
Alan Richardson has more than twenty years of professional IT experience,
working as a programmer and at every level of the testing hierarchy—from tester
through head of testing. Author of the books Selenium Simplified and Java For
Testers, Alan also has created online training courses to help people learn
technical web testing and Selenium WebDriver with Java. He now works as an
independent consultant, helping companies improve their use of automation,
agile, and exploratory technical testing. Alan posts his writing and training videos
on SeleniumSimplified.com, EvilTester.com, JavaForTesters.com, and
CompendiumDev.co.uk.
Automation Abstractions:
Page Objects and Beyond
Alan Richardson
@eviltester
www.SeleniumSimplified.com
www.EvilTester.com
www.CompendiumDev.co.uk
www.JavaForTesters.com
2
When you start writing automation for your projects, you quickly realize that you need to organize
and design the code.
You will write far more than “test” code; you also will write abstraction code because you want to
make tests easier to read and maintain.
But how do you design all this code? How do you organize and structure it?
●
Should you use a domain specific language?
●
Should you go keyword driven or use Gherkin?
●
Should you use page objects with POJO or Factories?
●
Do you create DOM level abstractions?
●
Where do domain models fit in?
Alan Richardson provides an overview of options available to you when modeling abstraction layers.
Based on his experience with many approaches on real-world commercial projects, Alan helps you
understand how to think about the modeling of abstraction layers.
Illustrated with a number of code examples, Alan shows you a variety of approaches and discusses
the pros and cons associated with each.
https://xp-dev.com/svn/AutomationAbstractions
3
What is Abstraction?
●
Modelling
●
Separation of concerns
●
Logical vs Physical
●
Functional vs Structural
●
Interfaces vs Implementations
●
Data / Entities / Persistence
●
Functionality / Task Flow
●
Goals / Strategies
●
Layers – GUI, DB, HTTP
●
Etc.
4
“I must create a system. or be
enslav'd by another Mans; I
will not reason & compare:
my business is to create”
William Blake, 1820
Jerusalem: The Emanation of the Giant Albion
http://www.blakearchive.org/exist/blake/archive/object.xq?objectid=jerusalem.e.illbk.10&java=no
5
Example Test Without
Abstraction
@Test
public void canCreateAToDoWithNoAbstraction(){
driver.get("http://todomvc.com/architecture-examples/backbone/");
int originalNumberOfTodos = driver.findElements(
By.cssSelector("ul#todo-list li")).size();
WebElement createTodo = driver.findElement(By.id("new-todo"));
createTodo.click();
createTodo.sendKeys("new task");
createTodo.sendKeys(Keys.ENTER);
assertThat(driver.findElement(
By.id("filters")).isDisplayed(), is(true));
int newToDos = driver.findElements(
By.cssSelector("ul#todo-list li")).size();
assertThat(newToDos, greaterThan(originalNumberOfTodos));
}
@Before
public void startDriver(){
driver = new FirefoxDriver();
}
@After
public void stopDriver(){
driver.close();
driver.quit();
}
NoAbstractionTest.java
6
Example Test Without
Abstraction
@Test
public void canCreateAToDoWithNoAbstraction(){
driver.get("http://todomvc.com/architecture-examples/backbone/");
int originalNumberOfTodos = driver.findElements(
By.cssSelector("ul#todo-list li")).size();
WebElement createTodo = driver.findElement(By.id("new-todo"));
createTodo.click();
createTodo.sendKeys("new task");
createTodo.sendKeys(Keys.ENTER);
assertThat(driver.findElement(
By.id("filters")).isDisplayed(), is(true));
int newToDos = driver.findElements(
By.cssSelector("ul#todo-list li")).size();
assertThat(newToDos, greaterThan(originalNumberOfTodos));
}
@Before
public void startDriver(){
driver = new FirefoxDriver();
}
@After
public void stopDriver(){
driver.close();
driver.quit();
}
NoAbstractionTest.java
But this does use some
abstraction layers
Firefox Browser Abstraction
WebDriver Generic Browser Abstraction
WebElement Generic Element Abstraction
Locator AbstractionLocator Abstractions
Manipulation Abstractions
7
WebDriver provides abstractions
●
Browser
●
DOM
●
Web Element
Tool vendors gain value from generic abstractions.
You gain value from 'domain' abstractions.
8
Example Test With Abstraction
@Test
public void canCreateAToDoWithAbstraction(){
TodoMVCUser user =
new TodoMVCUser(driver, new TodoMVCSite());
user.opensApplication().and().createNewToDo("new task");
ApplicationPageFunctional page =
new ApplicationPageFunctional(driver,
new TodoMVCSite());
assertThat(page.getCountOfTodoDoItems(), is(1));
assertThat(page.isFooterVisible(), is(true));
}
@Before
public void startDriver(){
driver = new FirefoxDriver();
}
@After
public void stopDriver(){
driver.close();
driver.quit();
}
NoAbstractionTest.java
9
Why Abstraction?
●
Change implementations
●
Single Responsibility – only changes when
necessary
●
Makes automation readable and maintainable
●
We can unit test some of our test code
●
etc.
10
Some Abstraction Layer Categories
1) Data
– Generic Data Abstractions e.g. email, postcode
2) Physical
– Physical layout of your application e.g. pages,
components
– Navigation across pages
3) Domain
– Your application Entities domain e.g. user, account
4) Logical
– User actions, workflows
11
Common Automation Abstractions
●
Page Objects: pages, components, widgets
●
Dom Element Abstractions: select, textbox, etc.
●
Domain Objects: user, account, order
●
Gherkin (Given/When/And/Then)
●
Domain Specific Languages: code, keywords
●
...
13
Abstraction != Implementation
●
Abstraction != Tool / Framework /
Implementation
●
Gherkin != Cucumber
●
Page Object != Page Factory / Slow Loadable
●
DSL != Keyword Driven
If we want to get good at abstraction then we
need to model, split apart, make the relationships
clear, and be aware of our options.
15
A Page Object abstracts a Page
●
Often has methods for
– Opening the page
– Accessing elements
– Doing stuff, and navigating as a side-effect
– Logical high level functionality e.g. login
– Low level physical functionality e.g.
typeUsername, clickLoginButton
Should a Page Object be responsible for all of
this?
16
Page Object Design Decisions
●
What methods does it have?
– Functional
●
login(username, password),
●
loginAs(user)
– Structural
●
enterName(username), enterPassword(password),
clickLogin(), submitLoginForm(username, password)
●
Does it expose elements or not?
– public WebElement loginButton;
– public WebElement getLoginButton();
– public clickLoginButton();
17
Page Object Functionality
Approaches
●
Expose WebElements Directly
– Leads to WebElement Abstractions
– public WebElement userNameField;
●
Hide WebElements behind physical functional
methods e.g. typeUserName("bob");
●
Logical helper methods e.g.
loginAs(name,pass)
●
Layers of Page Objects
– Physical
– Logical
18
Navigation Design Decisions
●
Does a Page Object return other pages?
public IssueListPage submit(){
driver.findElement(By.id(“submit”)).click();
return new IssueListPage(driver);
}
●
Or Navigate implicitly after interactions
●
Or have navigation objects
19
Implicit or Explicit Wait?
●
Implicit Wait
●
Explicit Wait
driver.manage().timeouts().
implicitlyWait(0L, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver,15);
wait.until(ExpectedConditions.elementToBeClickable
(By.id("filters")));
driver.manage().timeouts().
implicitlyWait(15L, TimeUnit.SECONDS);
assertThat(driver.findElement(
By.id("filters")).isDisplayed()
, is(true));
Example: 'NoAbstractionTest.java'
20
Implementing Page Objects
●
POJO
– Plain object, driver in constructor, methods use
driver.<method>
●
Page Factory
– Annotated elements, lazy instantiation via reflection
●
LoadableComponent
– Common interface (load, isLoaded), isLoaded
throws Error
●
SlowLoadableComponent
– Common interface, waits for on isLoaded
●
Other approaches?
21
Example Implementations
22
POJO
●
'ApplicationPage.java'
– Used in 'SequentialCreationOfTest.java'
– Not much refactoring in the example
●
Simple Class
●
WebDriver passed to constructor
●
Composition of any components
●
e.g.
– com.seleniumsimplified.todomvc.page.pojo
– 'ApplicationPage.java'
●
Not much refactoring in the example
24
Functional vs Structural
●
Functional
– loginAs(username, password)
●
Structural
– enterUsername
– enterPassword
– clickLoginButton
– submitLoginForm(username, password)
25
Functional Vs Structural Example
●
One way of answering “what methods to put on
a page object”
– Is it functional / behavioural?
– Is it structural / Physical?
●
Functional 'uses' Structural implementation
●
Why?
– Sometimes it is just a naming difference
– Handling exceptions in functional but not structural
– Higher level methods in Functional
– Different concepts e.g. deleteLastItem
26
Page Factory
●
Annotate fields with @FindBy
●
Instantiate in constructor using
PageFactory.initElements
– Can create your own page factory initialiser
●
Avoids boilerplate accessor methods
●
Fast to create Page Objects
●
Might become harder to expand and maintain
27
Page Factory Example
@FindBy(how = How.CSS, using="#todo-count strong")
private WebElement countElementStrong;
@FindBy(how = How.CSS, using="#todo-count")
private WebElement countElement;
@FindBy(how = How.CSS, using="#filters li a")
List<WebElement> filters;
@FindBy(how = How.ID, using="clear-completed")
List<WebElement> clearCompletedAsList;
@FindBy(how = How.ID, using="clear-completed")
WebElement clearCompletedButton;
public ApplicationPageStructuralFactory(WebDriver driver, TodoMVCSite todoMVCSite) {
PageFactory.initElements(driver, this);
this.driver = driver;
...
28
SlowLoadableComponent
●
Some pages and components need
synchronisation to wait till they are ready
– One approach – SlowLoadableComponent adds
responsibility for waiting, to the page
● extend SlowLoadableComponent
●
Standard interface for synchronisation on load
– get()
●
If isLoaded then return this Else load
●
While not loaded{ wait for 200 millseconds}
– Implement load and isLoaded
29
Fluent Page Objects
todoMVC = new ApplicationPageFunctionalFluent(
driver, todoMVCSite);
todoMVC.get();
todoMVC.enterNewToDo("First Completed Item").
and().
toggleCompletionOfLastItem().
then().
enterNewToDo("Still to do this").
and().
enterNewToDo("Still to do this too").
then().
filterOnCompleted();
30
Fluent Page Objects
●
Methods return the page object or other objects
instead of void
– void clickDeleteButton();
– PageObject clickDeleteButton();
●
Syntactic sugar methods:
– and(), then(), also()
●
Can work well at high levels of abstraction and
when no navigation involved
●
Train Wreck?
31
Navigation Options
●
Direct in Test: page.get(); page.waitFor();
●
Instantiate new pages based on test flow
– Navigation as side-effect, may have to bypass 'get'
– Loadable pages, non-loadable, support classes
●
Page Object methods might return other Pages
– e.g. a method on the login page might be
●
MyAccountPage clickLogin();
●
We might use navigation objects
– direct, Jump.to(MyAccountPage.class)
– path based (current page → desired page)
●
Navigate.to(MyAccountPage.class)
33
Page Objects & Domain Objects
●
Instead of
– todoMVC.enterNewToDo(“New Item”)
●
We could have have
– ToDoItem newItem = new ToDoItem(“New Item”);
– todoMVC.enterNewToDo(newItem);
●
See code in DomainBasedTest
34
Domain Objects That Span Logical
& Physical
e.g. User
●
user.createNewToDo(“new item”)
●
user.createNewToDo(newItem)
●
See use in NoAbstractionTest
35
Sometimes it is possible to over
think this stuff
●
Don't let thinking about this slow you down
●
Conduct experiments
●
Refactor
●
Rethink if
– you are maintaining too much
– your abstraction layer stops you doing stuff
– you are 'working around' your abstraction layers
36
Element
Abstractions
37
Element Abstraction Example
●
Would you include 'toggle'?
public interface Checkbox {
public boolean isChecked();
public Checkbox check();
public Checkbox uncheck();
public Checkbox toggle();
}
38
Element Abstractions
●
Existing support classes: Select,
●
Possible: TextBox, Checkbox, TextBox, File etc.
●
Can enforce Semantics
– Checkbox: isChecked, check(), uncheck(), toggle()
– TextBox: clear(), enterText()
– etc.
●
Pass back from Page Objects into test?
39
Element Abstraction Pros and Cons
●
May have to create a custom page factory
●
Can help 'restrict' code i.e. check or uncheck,
rather than click, enforces 'semantics'
●
If you create them...
– allow return WebElement
●
so that I can go beyond the abstraction layer if I need to.
Not required if it is just a WebElement wrapper.
40
Component Abstractions
●
Shared Components/Widgets on the page
●
e.g.
– VisibleToDoEntry, VisibleToDoList
– Filters, Footer, Header, etc.
●
Could have 'functional' representation for
repeated items e.g. login forms
●
Could have 'structural' representation
●
Likely use : page object composition
41
Component Abstraction Example
TodoEntry todo = page.getToDoEntryAt(lastItemPosition);
todo.markCompleted();
Instead of
page.markTodoCompleted(lastItemPosition);
42
Gherkin as an abstraction layer
●
Implement steps using highest appropriate
abstraction layer
●
CucumberJVM as 'DSL implementor'
●
'Expressibility' vs 'Step Re-use'
●
See todomvc.feature and ToDoMvcSteps
Feature: We can create and edit To Do lists in ToDoMvc
We want to amend todos in ToDoMVC because that is
the set of exercises on the abstraction tutorial
Scenario: Create a ToDo Item
Given a user opens a blank ToDoMVC page
When the user creates a todo "new task"
Then they see 1 todo item on the page
43
My modeling biases
●
Driver
– Inject so instantiate any page or component as
required/desired at any time
●
Explicit Synchronisation
– To make sure that the desired object is available
and ready for use (as defined by synchronisation)
●
Navigation
– Implicit (via taking action e.g. click)
– Explicit Navigation Object, not in page object
●
Open/jump (via driver.get)
●
To (state model from current, to desired)
44
My modeling biases
●
Page Objects
– Physical
●
abstract the 'real world'
– Components
●
For common features on the page
– Logical
●
abstract the functionality
●
Sometimes these are entity methods not page objects
– e.g. user.registers().and().logsin()
●
I tend not to....
– abstract WebElements
45
My modeling biases
●
I tend not to....
– abstract WebElements
– Use inheritence to create a model of the app
●
e.g. MyAppPage extends GenericAppPage
– Use 3rd
party abstractions on top of WebDriver
47
Are there rights and wrongs?
●
Right / Wrong?
●
Decisions?
●
Project/Team/Organisation Standards?
Identify your own biases -
Experiment
Recognise your decisions
48
Decisions
●
The 'limits' and overlap of Abstraction Layers
●
Build it now, or 'refactor to' later
●
How much change is anticipated?
– To which layer? GUI, Business domain, Workflow?
●
Who is working with the automation code?
– Skill levels? Support needed?
●
How/When with the automation execute?
49
“To the creative mind there is
no right or wrong. Every
action is an experiment, and
every experiment yields its
fruit in knowledge.”
The Illuminatus Trilogy
Robert Anton Wilson
50
Other Useful Links
●
Jeff “Cheezy” Morgan – page-object ruby gem,
data_magic gem and stareast code
– https://github.com/cheezy?tab=repositories
●
Marcus Merrell
– Self-Generating Test Artifacts for Selenium/WebDriver
– https://www.youtube.com/watch?v=mSCFsUOgPpw
●
Anand Ramdeo
– One Step at a Time
– https://www.youtube.com/watch?v=dFPgzH_XP1I
52
Homework
●
Using the code at
https://xp-dev.com/svn/AutomationAbstractions/
– Compare the different implementations under 'main'
●
com.seleniumsimplified.todomvc.page
– Investigate how the Page Objects delegate to each
other, and the Domain Objects use Page Objects
– Examine the 'test' usage of the Page Objects and
Domain Objects
– Examine the different navigation approaches

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Exploratory Testing
Exploratory TestingExploratory Testing
Exploratory Testing
 
React js
React jsReact js
React js
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Thinking in react
Thinking in reactThinking in react
Thinking in react
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Javascript
JavascriptJavascript
Javascript
 
Web Designing
Web Designing Web Designing
Web Designing
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ....NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
 
Test Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and CucumberTest Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and Cucumber
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Java script basics
Java script basicsJava script basics
Java script basics
 
QSpiders - Automation using Selenium
QSpiders - Automation using SeleniumQSpiders - Automation using Selenium
QSpiders - Automation using Selenium
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
AngularJS
AngularJSAngularJS
AngularJS
 

Andere mochten auch

CoMES-Pulse-(Newsletter)
CoMES-Pulse-(Newsletter)CoMES-Pulse-(Newsletter)
CoMES-Pulse-(Newsletter)
Anubhav Porwal
 
Understanding print technologies powerpoint
Understanding print technologies powerpointUnderstanding print technologies powerpoint
Understanding print technologies powerpoint
Hussain M
 

Andere mochten auch (16)

Testing Application Security: The Hacker Psyche Exposed
Testing Application Security: The Hacker Psyche ExposedTesting Application Security: The Hacker Psyche Exposed
Testing Application Security: The Hacker Psyche Exposed
 
Successful Property Procurement: Another Amazing SJREI Event
Successful Property Procurement: Another Amazing SJREI EventSuccessful Property Procurement: Another Amazing SJREI Event
Successful Property Procurement: Another Amazing SJREI Event
 
Jon Bach: On Testing
Jon Bach: On TestingJon Bach: On Testing
Jon Bach: On Testing
 
A Path through the Jungle: Validating a Test Automation System for the FDA
A Path through the Jungle: Validating a Test Automation System for the FDAA Path through the Jungle: Validating a Test Automation System for the FDA
A Path through the Jungle: Validating a Test Automation System for the FDA
 
Doug Duncan, Fannie Mae Chief Economist, Presentation at SJREI
Doug Duncan, Fannie Mae Chief Economist, Presentation at SJREIDoug Duncan, Fannie Mae Chief Economist, Presentation at SJREI
Doug Duncan, Fannie Mae Chief Economist, Presentation at SJREI
 
Sjreia reia may 15
Sjreia reia may 15Sjreia reia may 15
Sjreia reia may 15
 
Toward a Well-Run, Cross-Functional, High-Performance Team
Toward a Well-Run, Cross-Functional, High-Performance TeamToward a Well-Run, Cross-Functional, High-Performance Team
Toward a Well-Run, Cross-Functional, High-Performance Team
 
CoMES-Pulse-(Newsletter)
CoMES-Pulse-(Newsletter)CoMES-Pulse-(Newsletter)
CoMES-Pulse-(Newsletter)
 
Establishing an Agile Testing Culture
Establishing an Agile Testing CultureEstablishing an Agile Testing Culture
Establishing an Agile Testing Culture
 
Conveying Verbal Messages
Conveying Verbal MessagesConveying Verbal Messages
Conveying Verbal Messages
 
Arizona Economic Housing Outlook
Arizona Economic Housing OutlookArizona Economic Housing Outlook
Arizona Economic Housing Outlook
 
Checking Performance along Your Build Pipeline
Checking Performance along Your Build PipelineChecking Performance along Your Build Pipeline
Checking Performance along Your Build Pipeline
 
Understanding print technologies powerpoint
Understanding print technologies powerpointUnderstanding print technologies powerpoint
Understanding print technologies powerpoint
 
Inside the Entrepreneural Mind
Inside the Entrepreneural MindInside the Entrepreneural Mind
Inside the Entrepreneural Mind
 
Educational Business Plan
Educational Business PlanEducational Business Plan
Educational Business Plan
 
Research on Negative Effects Of Using Social Media
Research on Negative Effects Of Using Social MediaResearch on Negative Effects Of Using Social Media
Research on Negative Effects Of Using Social Media
 

Ähnlich wie Automation Abstractions: Page Objects and Beyond

Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"
Fwdays
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Julien Lecomte
 
Stepin evening presented
Stepin evening presentedStepin evening presented
Stepin evening presented
Vijayan Reddy
 

Ähnlich wie Automation Abstractions: Page Objects and Beyond (20)

Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 
Good practices for debugging Selenium and Appium tests
Good practices for debugging Selenium and Appium testsGood practices for debugging Selenium and Appium tests
Good practices for debugging Selenium and Appium tests
 
An Introduction to Web Components
An Introduction to Web ComponentsAn Introduction to Web Components
An Introduction to Web Components
 
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
 
Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"
 
Crash Course in AngularJS + Ionic (Deep dive)
Crash Course in AngularJS + Ionic (Deep dive)Crash Course in AngularJS + Ionic (Deep dive)
Crash Course in AngularJS + Ionic (Deep dive)
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
 
Session on Selenium Powertools by Unmesh Gundecha
Session on Selenium Powertools by Unmesh GundechaSession on Selenium Powertools by Unmesh Gundecha
Session on Selenium Powertools by Unmesh Gundecha
 
BDD with SpecFlow and Selenium
BDD with SpecFlow and SeleniumBDD with SpecFlow and Selenium
BDD with SpecFlow and Selenium
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
 
Selenium Testing Training in Bangalore
Selenium Testing Training in BangaloreSelenium Testing Training in Bangalore
Selenium Testing Training in Bangalore
 
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP AnywayI Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSGDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
 
Introduction to Selenium and Test Automation
Introduction to Selenium and Test AutomationIntroduction to Selenium and Test Automation
Introduction to Selenium and Test Automation
 
Stepin evening presented
Stepin evening presentedStepin evening presented
Stepin evening presented
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
 

Mehr von TechWell

Mehr von TechWell (20)

Failing and Recovering
Failing and RecoveringFailing and Recovering
Failing and Recovering
 
Instill a DevOps Testing Culture in Your Team and Organization
Instill a DevOps Testing Culture in Your Team and Organization Instill a DevOps Testing Culture in Your Team and Organization
Instill a DevOps Testing Culture in Your Team and Organization
 
Test Design for Fully Automated Build Architecture
Test Design for Fully Automated Build ArchitectureTest Design for Fully Automated Build Architecture
Test Design for Fully Automated Build Architecture
 
System-Level Test Automation: Ensuring a Good Start
System-Level Test Automation: Ensuring a Good StartSystem-Level Test Automation: Ensuring a Good Start
System-Level Test Automation: Ensuring a Good Start
 
Build Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test StrategyBuild Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test Strategy
 
Testing Transformation: The Art and Science for Success
Testing Transformation: The Art and Science for SuccessTesting Transformation: The Art and Science for Success
Testing Transformation: The Art and Science for Success
 
Implement BDD with Cucumber and SpecFlow
Implement BDD with Cucumber and SpecFlowImplement BDD with Cucumber and SpecFlow
Implement BDD with Cucumber and SpecFlow
 
Develop WebDriver Automated Tests—and Keep Your Sanity
Develop WebDriver Automated Tests—and Keep Your SanityDevelop WebDriver Automated Tests—and Keep Your Sanity
Develop WebDriver Automated Tests—and Keep Your Sanity
 
Ma 15
Ma 15Ma 15
Ma 15
 
Eliminate Cloud Waste with a Holistic DevOps Strategy
Eliminate Cloud Waste with a Holistic DevOps StrategyEliminate Cloud Waste with a Holistic DevOps Strategy
Eliminate Cloud Waste with a Holistic DevOps Strategy
 
Transform Test Organizations for the New World of DevOps
Transform Test Organizations for the New World of DevOpsTransform Test Organizations for the New World of DevOps
Transform Test Organizations for the New World of DevOps
 
The Fourth Constraint in Project Delivery—Leadership
The Fourth Constraint in Project Delivery—LeadershipThe Fourth Constraint in Project Delivery—Leadership
The Fourth Constraint in Project Delivery—Leadership
 
Resolve the Contradiction of Specialists within Agile Teams
Resolve the Contradiction of Specialists within Agile TeamsResolve the Contradiction of Specialists within Agile Teams
Resolve the Contradiction of Specialists within Agile Teams
 
Pin the Tail on the Metric: A Field-Tested Agile Game
Pin the Tail on the Metric: A Field-Tested Agile GamePin the Tail on the Metric: A Field-Tested Agile Game
Pin the Tail on the Metric: A Field-Tested Agile Game
 
Agile Performance Holarchy (APH)—A Model for Scaling Agile Teams
Agile Performance Holarchy (APH)—A Model for Scaling Agile TeamsAgile Performance Holarchy (APH)—A Model for Scaling Agile Teams
Agile Performance Holarchy (APH)—A Model for Scaling Agile Teams
 
A Business-First Approach to DevOps Implementation
A Business-First Approach to DevOps ImplementationA Business-First Approach to DevOps Implementation
A Business-First Approach to DevOps Implementation
 
Databases in a Continuous Integration/Delivery Process
Databases in a Continuous Integration/Delivery ProcessDatabases in a Continuous Integration/Delivery Process
Databases in a Continuous Integration/Delivery Process
 
Mobile Testing: What—and What Not—to Automate
Mobile Testing: What—and What Not—to AutomateMobile Testing: What—and What Not—to Automate
Mobile Testing: What—and What Not—to Automate
 
Cultural Intelligence: A Key Skill for Success
Cultural Intelligence: A Key Skill for SuccessCultural Intelligence: A Key Skill for Success
Cultural Intelligence: A Key Skill for Success
 
Turn the Lights On: A Power Utility Company's Agile Transformation
Turn the Lights On: A Power Utility Company's Agile TransformationTurn the Lights On: A Power Utility Company's Agile Transformation
Turn the Lights On: A Power Utility Company's Agile Transformation
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Automation Abstractions: Page Objects and Beyond

  • 1. !! T9 Test!Automation! 10/16/2014!11:15:00!AM! ! Automation Abstractions: Page Objects and Beyond ! Presented by: Alan Richardson Compendium Developments ! ! ! Brought(to(you(by:( ( ( ( 340!Corporate!Way,!Suite!300,!Orange!Park,!FL!32073! 888G268G8770!H!904G278G0524!H!sqeinfo@sqe.com!H!www.sqe.com! !
  • 2. Alan Richardson Compendium Developments Alan Richardson has more than twenty years of professional IT experience, working as a programmer and at every level of the testing hierarchy—from tester through head of testing. Author of the books Selenium Simplified and Java For Testers, Alan also has created online training courses to help people learn technical web testing and Selenium WebDriver with Java. He now works as an independent consultant, helping companies improve their use of automation, agile, and exploratory technical testing. Alan posts his writing and training videos on SeleniumSimplified.com, EvilTester.com, JavaForTesters.com, and CompendiumDev.co.uk.
  • 3. Automation Abstractions: Page Objects and Beyond Alan Richardson @eviltester www.SeleniumSimplified.com www.EvilTester.com www.CompendiumDev.co.uk www.JavaForTesters.com 2 When you start writing automation for your projects, you quickly realize that you need to organize and design the code. You will write far more than “test” code; you also will write abstraction code because you want to make tests easier to read and maintain. But how do you design all this code? How do you organize and structure it? ● Should you use a domain specific language? ● Should you go keyword driven or use Gherkin? ● Should you use page objects with POJO or Factories? ● Do you create DOM level abstractions? ● Where do domain models fit in? Alan Richardson provides an overview of options available to you when modeling abstraction layers. Based on his experience with many approaches on real-world commercial projects, Alan helps you understand how to think about the modeling of abstraction layers. Illustrated with a number of code examples, Alan shows you a variety of approaches and discusses the pros and cons associated with each. https://xp-dev.com/svn/AutomationAbstractions
  • 4. 3 What is Abstraction? ● Modelling ● Separation of concerns ● Logical vs Physical ● Functional vs Structural ● Interfaces vs Implementations ● Data / Entities / Persistence ● Functionality / Task Flow ● Goals / Strategies ● Layers – GUI, DB, HTTP ● Etc. 4 “I must create a system. or be enslav'd by another Mans; I will not reason & compare: my business is to create” William Blake, 1820 Jerusalem: The Emanation of the Giant Albion http://www.blakearchive.org/exist/blake/archive/object.xq?objectid=jerusalem.e.illbk.10&java=no
  • 5. 5 Example Test Without Abstraction @Test public void canCreateAToDoWithNoAbstraction(){ driver.get("http://todomvc.com/architecture-examples/backbone/"); int originalNumberOfTodos = driver.findElements( By.cssSelector("ul#todo-list li")).size(); WebElement createTodo = driver.findElement(By.id("new-todo")); createTodo.click(); createTodo.sendKeys("new task"); createTodo.sendKeys(Keys.ENTER); assertThat(driver.findElement( By.id("filters")).isDisplayed(), is(true)); int newToDos = driver.findElements( By.cssSelector("ul#todo-list li")).size(); assertThat(newToDos, greaterThan(originalNumberOfTodos)); } @Before public void startDriver(){ driver = new FirefoxDriver(); } @After public void stopDriver(){ driver.close(); driver.quit(); } NoAbstractionTest.java 6 Example Test Without Abstraction @Test public void canCreateAToDoWithNoAbstraction(){ driver.get("http://todomvc.com/architecture-examples/backbone/"); int originalNumberOfTodos = driver.findElements( By.cssSelector("ul#todo-list li")).size(); WebElement createTodo = driver.findElement(By.id("new-todo")); createTodo.click(); createTodo.sendKeys("new task"); createTodo.sendKeys(Keys.ENTER); assertThat(driver.findElement( By.id("filters")).isDisplayed(), is(true)); int newToDos = driver.findElements( By.cssSelector("ul#todo-list li")).size(); assertThat(newToDos, greaterThan(originalNumberOfTodos)); } @Before public void startDriver(){ driver = new FirefoxDriver(); } @After public void stopDriver(){ driver.close(); driver.quit(); } NoAbstractionTest.java But this does use some abstraction layers Firefox Browser Abstraction WebDriver Generic Browser Abstraction WebElement Generic Element Abstraction Locator AbstractionLocator Abstractions Manipulation Abstractions
  • 6. 7 WebDriver provides abstractions ● Browser ● DOM ● Web Element Tool vendors gain value from generic abstractions. You gain value from 'domain' abstractions. 8 Example Test With Abstraction @Test public void canCreateAToDoWithAbstraction(){ TodoMVCUser user = new TodoMVCUser(driver, new TodoMVCSite()); user.opensApplication().and().createNewToDo("new task"); ApplicationPageFunctional page = new ApplicationPageFunctional(driver, new TodoMVCSite()); assertThat(page.getCountOfTodoDoItems(), is(1)); assertThat(page.isFooterVisible(), is(true)); } @Before public void startDriver(){ driver = new FirefoxDriver(); } @After public void stopDriver(){ driver.close(); driver.quit(); } NoAbstractionTest.java
  • 7. 9 Why Abstraction? ● Change implementations ● Single Responsibility – only changes when necessary ● Makes automation readable and maintainable ● We can unit test some of our test code ● etc. 10 Some Abstraction Layer Categories 1) Data – Generic Data Abstractions e.g. email, postcode 2) Physical – Physical layout of your application e.g. pages, components – Navigation across pages 3) Domain – Your application Entities domain e.g. user, account 4) Logical – User actions, workflows
  • 8. 11 Common Automation Abstractions ● Page Objects: pages, components, widgets ● Dom Element Abstractions: select, textbox, etc. ● Domain Objects: user, account, order ● Gherkin (Given/When/And/Then) ● Domain Specific Languages: code, keywords ● ...
  • 9. 13 Abstraction != Implementation ● Abstraction != Tool / Framework / Implementation ● Gherkin != Cucumber ● Page Object != Page Factory / Slow Loadable ● DSL != Keyword Driven If we want to get good at abstraction then we need to model, split apart, make the relationships clear, and be aware of our options.
  • 10. 15 A Page Object abstracts a Page ● Often has methods for – Opening the page – Accessing elements – Doing stuff, and navigating as a side-effect – Logical high level functionality e.g. login – Low level physical functionality e.g. typeUsername, clickLoginButton Should a Page Object be responsible for all of this? 16 Page Object Design Decisions ● What methods does it have? – Functional ● login(username, password), ● loginAs(user) – Structural ● enterName(username), enterPassword(password), clickLogin(), submitLoginForm(username, password) ● Does it expose elements or not? – public WebElement loginButton; – public WebElement getLoginButton(); – public clickLoginButton();
  • 11. 17 Page Object Functionality Approaches ● Expose WebElements Directly – Leads to WebElement Abstractions – public WebElement userNameField; ● Hide WebElements behind physical functional methods e.g. typeUserName("bob"); ● Logical helper methods e.g. loginAs(name,pass) ● Layers of Page Objects – Physical – Logical 18 Navigation Design Decisions ● Does a Page Object return other pages? public IssueListPage submit(){ driver.findElement(By.id(“submit”)).click(); return new IssueListPage(driver); } ● Or Navigate implicitly after interactions ● Or have navigation objects
  • 12. 19 Implicit or Explicit Wait? ● Implicit Wait ● Explicit Wait driver.manage().timeouts(). implicitlyWait(0L, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver,15); wait.until(ExpectedConditions.elementToBeClickable (By.id("filters"))); driver.manage().timeouts(). implicitlyWait(15L, TimeUnit.SECONDS); assertThat(driver.findElement( By.id("filters")).isDisplayed() , is(true)); Example: 'NoAbstractionTest.java' 20 Implementing Page Objects ● POJO – Plain object, driver in constructor, methods use driver.<method> ● Page Factory – Annotated elements, lazy instantiation via reflection ● LoadableComponent – Common interface (load, isLoaded), isLoaded throws Error ● SlowLoadableComponent – Common interface, waits for on isLoaded ● Other approaches?
  • 13. 21 Example Implementations 22 POJO ● 'ApplicationPage.java' – Used in 'SequentialCreationOfTest.java' – Not much refactoring in the example ● Simple Class ● WebDriver passed to constructor ● Composition of any components ● e.g. – com.seleniumsimplified.todomvc.page.pojo – 'ApplicationPage.java' ● Not much refactoring in the example
  • 14. 24 Functional vs Structural ● Functional – loginAs(username, password) ● Structural – enterUsername – enterPassword – clickLoginButton – submitLoginForm(username, password)
  • 15. 25 Functional Vs Structural Example ● One way of answering “what methods to put on a page object” – Is it functional / behavioural? – Is it structural / Physical? ● Functional 'uses' Structural implementation ● Why? – Sometimes it is just a naming difference – Handling exceptions in functional but not structural – Higher level methods in Functional – Different concepts e.g. deleteLastItem 26 Page Factory ● Annotate fields with @FindBy ● Instantiate in constructor using PageFactory.initElements – Can create your own page factory initialiser ● Avoids boilerplate accessor methods ● Fast to create Page Objects ● Might become harder to expand and maintain
  • 16. 27 Page Factory Example @FindBy(how = How.CSS, using="#todo-count strong") private WebElement countElementStrong; @FindBy(how = How.CSS, using="#todo-count") private WebElement countElement; @FindBy(how = How.CSS, using="#filters li a") List<WebElement> filters; @FindBy(how = How.ID, using="clear-completed") List<WebElement> clearCompletedAsList; @FindBy(how = How.ID, using="clear-completed") WebElement clearCompletedButton; public ApplicationPageStructuralFactory(WebDriver driver, TodoMVCSite todoMVCSite) { PageFactory.initElements(driver, this); this.driver = driver; ... 28 SlowLoadableComponent ● Some pages and components need synchronisation to wait till they are ready – One approach – SlowLoadableComponent adds responsibility for waiting, to the page ● extend SlowLoadableComponent ● Standard interface for synchronisation on load – get() ● If isLoaded then return this Else load ● While not loaded{ wait for 200 millseconds} – Implement load and isLoaded
  • 17. 29 Fluent Page Objects todoMVC = new ApplicationPageFunctionalFluent( driver, todoMVCSite); todoMVC.get(); todoMVC.enterNewToDo("First Completed Item"). and(). toggleCompletionOfLastItem(). then(). enterNewToDo("Still to do this"). and(). enterNewToDo("Still to do this too"). then(). filterOnCompleted(); 30 Fluent Page Objects ● Methods return the page object or other objects instead of void – void clickDeleteButton(); – PageObject clickDeleteButton(); ● Syntactic sugar methods: – and(), then(), also() ● Can work well at high levels of abstraction and when no navigation involved ● Train Wreck?
  • 18. 31 Navigation Options ● Direct in Test: page.get(); page.waitFor(); ● Instantiate new pages based on test flow – Navigation as side-effect, may have to bypass 'get' – Loadable pages, non-loadable, support classes ● Page Object methods might return other Pages – e.g. a method on the login page might be ● MyAccountPage clickLogin(); ● We might use navigation objects – direct, Jump.to(MyAccountPage.class) – path based (current page → desired page) ● Navigate.to(MyAccountPage.class)
  • 19. 33 Page Objects & Domain Objects ● Instead of – todoMVC.enterNewToDo(“New Item”) ● We could have have – ToDoItem newItem = new ToDoItem(“New Item”); – todoMVC.enterNewToDo(newItem); ● See code in DomainBasedTest 34 Domain Objects That Span Logical & Physical e.g. User ● user.createNewToDo(“new item”) ● user.createNewToDo(newItem) ● See use in NoAbstractionTest
  • 20. 35 Sometimes it is possible to over think this stuff ● Don't let thinking about this slow you down ● Conduct experiments ● Refactor ● Rethink if – you are maintaining too much – your abstraction layer stops you doing stuff – you are 'working around' your abstraction layers 36 Element Abstractions
  • 21. 37 Element Abstraction Example ● Would you include 'toggle'? public interface Checkbox { public boolean isChecked(); public Checkbox check(); public Checkbox uncheck(); public Checkbox toggle(); } 38 Element Abstractions ● Existing support classes: Select, ● Possible: TextBox, Checkbox, TextBox, File etc. ● Can enforce Semantics – Checkbox: isChecked, check(), uncheck(), toggle() – TextBox: clear(), enterText() – etc. ● Pass back from Page Objects into test?
  • 22. 39 Element Abstraction Pros and Cons ● May have to create a custom page factory ● Can help 'restrict' code i.e. check or uncheck, rather than click, enforces 'semantics' ● If you create them... – allow return WebElement ● so that I can go beyond the abstraction layer if I need to. Not required if it is just a WebElement wrapper. 40 Component Abstractions ● Shared Components/Widgets on the page ● e.g. – VisibleToDoEntry, VisibleToDoList – Filters, Footer, Header, etc. ● Could have 'functional' representation for repeated items e.g. login forms ● Could have 'structural' representation ● Likely use : page object composition
  • 23. 41 Component Abstraction Example TodoEntry todo = page.getToDoEntryAt(lastItemPosition); todo.markCompleted(); Instead of page.markTodoCompleted(lastItemPosition); 42 Gherkin as an abstraction layer ● Implement steps using highest appropriate abstraction layer ● CucumberJVM as 'DSL implementor' ● 'Expressibility' vs 'Step Re-use' ● See todomvc.feature and ToDoMvcSteps Feature: We can create and edit To Do lists in ToDoMvc We want to amend todos in ToDoMVC because that is the set of exercises on the abstraction tutorial Scenario: Create a ToDo Item Given a user opens a blank ToDoMVC page When the user creates a todo "new task" Then they see 1 todo item on the page
  • 24. 43 My modeling biases ● Driver – Inject so instantiate any page or component as required/desired at any time ● Explicit Synchronisation – To make sure that the desired object is available and ready for use (as defined by synchronisation) ● Navigation – Implicit (via taking action e.g. click) – Explicit Navigation Object, not in page object ● Open/jump (via driver.get) ● To (state model from current, to desired) 44 My modeling biases ● Page Objects – Physical ● abstract the 'real world' – Components ● For common features on the page – Logical ● abstract the functionality ● Sometimes these are entity methods not page objects – e.g. user.registers().and().logsin() ● I tend not to.... – abstract WebElements
  • 25. 45 My modeling biases ● I tend not to.... – abstract WebElements – Use inheritence to create a model of the app ● e.g. MyAppPage extends GenericAppPage – Use 3rd party abstractions on top of WebDriver
  • 26. 47 Are there rights and wrongs? ● Right / Wrong? ● Decisions? ● Project/Team/Organisation Standards? Identify your own biases - Experiment Recognise your decisions 48 Decisions ● The 'limits' and overlap of Abstraction Layers ● Build it now, or 'refactor to' later ● How much change is anticipated? – To which layer? GUI, Business domain, Workflow? ● Who is working with the automation code? – Skill levels? Support needed? ● How/When with the automation execute?
  • 27. 49 “To the creative mind there is no right or wrong. Every action is an experiment, and every experiment yields its fruit in knowledge.” The Illuminatus Trilogy Robert Anton Wilson 50 Other Useful Links ● Jeff “Cheezy” Morgan – page-object ruby gem, data_magic gem and stareast code – https://github.com/cheezy?tab=repositories ● Marcus Merrell – Self-Generating Test Artifacts for Selenium/WebDriver – https://www.youtube.com/watch?v=mSCFsUOgPpw ● Anand Ramdeo – One Step at a Time – https://www.youtube.com/watch?v=dFPgzH_XP1I
  • 28. 52 Homework ● Using the code at https://xp-dev.com/svn/AutomationAbstractions/ – Compare the different implementations under 'main' ● com.seleniumsimplified.todomvc.page – Investigate how the Page Objects delegate to each other, and the Domain Objects use Page Objects – Examine the 'test' usage of the Page Objects and Domain Objects – Examine the different navigation approaches