Anda di halaman 1dari 347

Author Copy. Not For Distribution.

Selenium WebDriver

Author Copy. Not For Distribution.


Publishing-in-support-of,

EDUCREATION PUBLISHING
RZ 94, Sector - 6, Dwarka, New Delhi - 110075
Shubham Vihar, Mangla, Bilaspur, Chhattisgarh - 495001

Website: www.educreation.in
________________________________________________________________

© Copyright, Author

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted, in any form by any means, electronic, mechanical, magnetic, optical, chemical,
manual, photocopying, recording or otherwise, without the prior written consent of its writer.

ISBN: 978-1-61813-470-7
Price: ` 815.00

The opinions/ contents expressed in this book are solely of the author and do not represent
the opinions/ standings/ thoughts of Educreation. The book is released by using the
services of self-publishing house.

Printed in India

ii

Author Copy. Not For Distribution.


Selenium WebDriver
Software Automation Testing Secrets Revealed - Part2

Narayanan Palani

EDUCREATION PUBLISHING
(Since 2011)
www.educreation.in

iii

Author Copy. Not For Distribution.


iv

Author Copy. Not For Distribution.


Praise For The Book
"Its has an excellent articulation how to start and execute your
automation project using of Selenium Web Driver. If you want to Learn
Selenium Web Driver from a Practical point of view, close your eyes and
go for it"
-Raghavendra Mesta,Test Lead,Deutsche Bank.

"A very useful and timely book of great value to intelligent


automation practitioners. Great value for money. Loads of code samples
to practise and very well edited"
-Vimalaadhithan Lakshmikanthan, Test Manager
'"Software Automation Testing Secrets Revealed" is so much more
than just a 'how to' guide. Hands down it is the broadest 'user centric'
manual I have come across. While obviously written with the IT
community as its primary audience, SATSR is simplistically written with
a comprehensive explanation of the instructions, step-by-step guidance,
pertinent resource links and tons of related screenshots."
- Janet Aponte-Pagan, CTFL,Software
QA/QC Analyst at Skanska USA

"I prefer this book for any newbie to selenium. Like NP's previous
books, he again put his great practical experience and analysis in this
book. Several examples, sample codes and configuration snippets would
really help to learn practically, not just theoretically."
-Jagath Sathyanarayana, Automation & Service Virtualization
Consultant and Evangelist. Wipro Technologies, United Kingdom.

"I was learning Selenium Automation by myself and from Google.


Suddenly I saw the book "Software Automation Testing Secrets Revealed
- Selenium WebDriver" By Narayanan Palani and it was of great help.
The book is written in a very simple way and with lot of practical
examples which helps the tester to tackle the challenges in smart way."
-Sandipan Das,Test Lead, Commonwealth Bank of Australia

Author Copy. Not For Distribution.


"There are two ways of looking at it. Some people prefer websites
rather than books. But I go for a book to start learning the basics. This
book definitely helps. Overall I would give 4 stars to this solid book."
-Pratiksha Ugade,KJ Somaiya Institute,Mumbai

"Narayanan has nailed it again..!!! This book is beautifully knitted


with simplicity and exceptional coverage. It will minimise your effort
spent on Google for your day today tech solutions. I'd recommend this
book to the thrill-seeking crowd in the field Software Automation."
-Rajeev Gaur,Test Lead

"The book articulates well excellent solutions to the problems that


industry faces today. The book will be very handy who is working or
planning to make a career in software Test automation."
-Ajit Kumar Biswal,Test Lead

"The book is easy to read, informative, and complete. I would


caution against reading it cover-to-cover as there may be too much
information to process. Reading this book will help you to become the
automation engineer we all strive to be. I will recommend this book to all
my peers"
-Athira AM,QA Lead,Wipro Technologies.

"One of the fine edition on Selenium which helps you learn


automation. Concepts explicitly written with detailed information and
visuals to help user understand and take a leap forward."
-Shubham Joshi, Senior Business Analyst

"The book with rich content, self descriptive examples equal to


coaching classes & readers understand easily without any relevant
knowledge of programming language for sure"
-Jagan Kanniappan, ETL Test Automation Specialist

"This Book is a well written and well thought through book. There
is enough information to write selenium code in Java programming
language from scratch. This suits for both beginners and advance level
users"
- Rajkumar J. Bhojan, Principal Consultant,
Wipro Technologies, Boston, MA, USA.

vi

Author Copy. Not For Distribution.


"This is the complete guide for beginners and will help to save
hours of time. This book have simple steps and supported screen shots"
-Murugadass,Test Lead.

"Awesome writing with good technical coverage on TestNG and


reporting..!!! Excellent Narayanan Palani...!!!"
-Wilson Misquith,QA Test Lead

“It is really nice book , each and every basic concepts you have
explained nicely."
-Navya Padiyar, Test Specialist

"Looks really good and straightforward; Very helpful to new


comers!"
-Srikanth Varma,Test Specialist
"This book is very simple, easy to read and having clear concepts.
The author definitely knows about the topic and it's very easy to
understand. Very informative and I would recommend it to all my
friends."
- Shriti K, Test Engineer (SDET), USA

"Looks like you have explained the subject in such great


detail...indeed selenium secret is revealed"
-Deepa Tipnis, Test Specialist

"This book would definitely encourage and fulfil the thirst of young
automation engineers and beginners to achieve a great automation
experience. His handcrafted book will produce smart automation
engineers who can able to do the things 'just like that'..."
- Karthikeyan Sadaiyappan, Technical Lead.

vii

Author Copy. Not For Distribution.


Part 2:
Automation Software Applications using Selenium WebDriver, TestNG,
JUnit, Cucumber BDD within Eclipse based Java Projects and build an
extensive Data Driven Automation Framework which consists of
Screenshot capability, Log4J Integration, XSLT Reporting,
Parameterisation, Object Repositories, Excel Sheets based Data Input/
Outputs, Cross Browser Tests using Firefox, Chrome and Internet
Explorer. Enhance tests with Page Object Model, Reuse Selenium IDE
scripts to Load Testing using JMeter!

viii

Author Copy. Not For Distribution.


About The Author

Narayanan Palani

Narayanan Palani is endorsed as exceptional talent of UK within


digital technology sector by Tech City UK.
Being a leader of proven and renowned software testing industry,
Narayanan Palani volunteered to share technical knowledge through his
best-selling book series ‗Software Automation Testing Secrets Revealed‘
which ranks top amongst the books on computer science across APAC,
USA, UK and Japan markets. His well-designed GITHUB open-source
testing projects are accessed worldwide profusely and have been
assisting job seekers to get involved into junior testing jobs.

ix

Author Copy. Not For Distribution.


Being a leading test specialist and at the same time holding six
awards, fifteen international certifications, eight published research
papers and four books selling across the world, he continued to innovate
and implement cutting edge technologies as part of his recent roles. His
IBM professional certificate profilei is viewed worldwide and new
comers are being inspired to take interest in software testing profession.
He is also nominated for the ‗Testing Leader‘ of the year 2016.ii
His 51+ LinkedIniii recommendations are strong evidences of his
novel work as a testing leader, and the research papers such as Right
Brain Testing using Gestalt Psychologyiv is still referred by research
scholars for software testing R&D.
Apart from his spectacular personal records on software testing, he
has trained and developed at least twenty-one non-IT/fresher candidates
into software testing within a short period of one year, and surprisingly
most of them are proving their abilities as strong team members in
testing projects, and thus, his ambition of generating employability
among the job seekers has been materialized.

CERTIFICATIONS
 International Software Testing Qualifications Board-CTAL Test
Manager
 International Software Testing Qualifications Board-CTFL
 Certified Scrum Master

Author Copy. Not For Distribution.


 PRINCE2 Project Management Foundations
 ITIL Foundation Certification
 HP Accredited Integration Specialist in Application Security
 IBM Certified Specialist in Rational Appscan.
 HP Accredited Integration Specialist in Quality Center v9 and QTP
v9
 IBM Certified Rational Specialist in Test Management and Rational
Robot
 IBM Certified Solution Designer in Rational Functional Test
 IBM Certified Solution Designer in Rational Performance Test
 IBM Certified Solution Designer in Rational Manual Tester
 IBM Examinations in Requirements Gathering and Use Case 1 & 2

https://uk.linkedin.com/in/narayananpalani

xi

Author Copy. Not For Distribution.


Foreword Recommendation Code Reviewer
Ponsailapathi V Mukesh Adhvaryu Shweta Bhat
Framework Content Reviewer Selenium Topics
Reviewer Venkatesh VI Reviewer
Arrchana Mohan Dinesh Balaji

xii

Author Copy. Not For Distribution.


Ponsailapathy Viswanathan,
Director-Delivery, VirtusaPolaris
Ponsailapathi Viswanathan “Pons” has over 22+ years of IT experience
in Travel, Banking and Insurance industries, mainly focusing on
software delivery and solution. He has played key role in building the
testing practice at Europe for his organization and handled strategic
roles in the design and set-up of TCoE engagements for global banks
across Americas, Europe & Middle East.
He led the set-up of near-shore delivery center for his organization
in Northern Ireland, UK to service European customers and successfully
established global delivery teams which can operate in tri-coastal model
for global banks.
Also built technology CoEs for mobile testing, security testing &
nurtured test automation, performance engineering practices to develop
innovative solutions for Banking & Insurance customers.

https://www.linkedin.com/in/ponsailapathi-viswanathan-
224a755

xiii

Author Copy. Not For Distribution.


Foreword

Information technology is one of the challenging and rewarding industry.


As per NASSCOM & other market trends the global testing market is
estimated to reach US $50 Billion by 2020. QA enterprises and test
automation engineers will find exciting opportunities in the area of big
data, mobile and API testing. Test automation skill is going to be one of
the most wanted skill in Y2017 and beyond.
Considering the industry demand, there is a need to up skill
ourselves continuously to stay ahead of the game and reap the benefits of
latest technology. Now the industry is looking for cost effective
solutions, tools like Selenium will be the best fit to manage the client
requirements both in terms of technical complexity and cost.
To pick-up the nuances of test automation quickly, Narayanan
Palani has scripted this book very nicely with simple examples based on
his experience.
As an automation architect, Narayanan Palani has successfully
implemented robust test automation utilities for complex trading
applications in banking space. His penchant for perfection and innovative
approach has created a huge positive impact in test automation projects
with excellent results in terms of ROI (Return on Investment). Test
automation techniques orchestrated by him made a difference in test
automation strategy and maintenance of the test scripts.
Most of the people, don‘t share their hard learning's or techniques to
others easily. Hats off to Narayanan Palani for his initiative to publish his
decade long experience in the Test automation to aspiring candidates. He
has articulated the end to end test automation techniques effortlessly in
line with industry best practices. The secrets revealed here will enable
the reader to build the test automation suite with ease.
I take this opportunity to congratulate Narayanan Palani for his
effort to spread the learning‘s with testing community! Looking forward
to see more such products from him in near future!
Happy reading!
-Ponsailapathy Viswanathan,
Director-Delivery, VirtusaPolaris

W
xiv

Author Copy. Not For Distribution.


Mukesh Adhvaryu
♛ Exceptional Talent of the UK
Director & Co-founder, M&M Info-Tech Ltd. UK

16 Years of experience in Analysis, Design, Development and


Implementation of Web & Windows Applications, Object Oriented design
and development.

Awards & Achievements


2014: National Award for Outstanding Services in Railways - conferred
by Ministry of Railways India for developing Western Railway Data
Management System & Report Automation module.

Certificate of Merits
 2005 – Office Data Management System
 2004 – Coach Management System
 2004 – Block Analysis System
 2002 – FOIS Analytical Reporting System

My recent projects
MnMFramework 1.0 – alternative light weight components framework
MnMVirtualControlFramework 1.0-Innovative virtual controls
framework

My previous projects

xv

Author Copy. Not For Distribution.


Universal Data Analysis Tool, Generic Functions Library, Report
Automation Library and Data Access Core Library.

https://www.linkedin.com/in/mukesh-adhvaryu-79500219

xvi

Author Copy. Not For Distribution.


Recommendation

In March 2016, I started to prepare for my Exceptional Talent Visa to be


endorsed by TechCity UK. After going through guidance available on
official TechCity websitev, it was clear to me that this visa was a covet
one and the guidance was vague enough to keep anyone busy speculating
as to what exactly one should and could submit as evidence to meet
mandatory and qualified criteria. This visa was so important for me as its
outcome was to decide whether my company will be based in Mumbai or
London. So I wanted to have no stones unturned to make sure I prepared
my case the best I could and as such I was desperately longing for an
appropriate advice from someone who had been to this situation and
emerged as successful exceptional talent of the UK. I started searching
online for the one and I stumbled upon a name of Mr Narayanan Palani. I
made LinkedIn connection invitation to him and to my pleasant surprise
he accepted it and that is how a dawn of great professional relationship
between him and myself happened. He helped me with his valuable
inputs regarding my Tech Visa application and I have no doubt in my
mind that he contributed in my successful exceptional talent visa
application. I respect him a lot for his noble act of helping me when I
was in need.
To quantify a talent in digital technology is an extremely difficult
task and even to prepare documentation requires an exceptional talent! It
takes few sleepless nights to figure out as to how you can prove yourself
either as an established world leader in the field of your expertise or at-
least you have potential to be so in future. It‘s a real tricky part of the
process. In my case, thankfully I had the National Award from the Indian
Railways for Report Automation project I did in year 2014. Although my
work in report automation differs from the phenomena of test
automation, the fundamental concept remains the same as the core
objective is ‗Automation‘ of some process.
I have read this book from that perspective and I am glad that I find
it extremely useful to further expand my idea of automation as a core
ideology in various processes be it software testing or data reporting or
even industrial processing. I am a hard-core C# fan but I do live in
realistic world and must acknowledge the power of java and wide spread
appeal of java based applications. So my friend Narayanan is right when
he emphasizes on java for the beginners. The book is structured
beautifully and it provides simple process flow to learn and practise.
xvii

Author Copy. Not For Distribution.


Narayanan has this panache to make things simply simple and
appealing to masses and I am sure this book will provide very precious
reference base for all who want to pursue career in test automation. I
especially like the part where the book starts revealing Object Capturing
Techniques for Automation Testing which then further narrows down to
fundamentals of ‗XPath‘. Starting from page 36 to 46, the book provides
very helpful insights on DOM inspection and search techniques and tools
available and how they can be used to explore the power of XPath. I
believe this particular topic has universal appeal as it is useful in some
other contexts as well. I had used XPath extensively with Mozilla web
browser control to search web page content required for automated data
downloading and report automation. As for the manipulation of the web
pages, I relied heavily upon java script to be executed through JSContext
object available with the Mozilla Web Browser Control.
Overall, I would like to rate the coverage of various topics such as
Software Quality Management, Technology Change Management and
Test scripting techniques to be of an excellent quality 4.7 out of 5! I also
concur that the section on ―Proof Of Concept (PoC)- Selenium
WebDriver Based Test Automation Framework‖ is also written with
extreme care and panache and it indeed provides in-depth domain
knowledge. And yes the FAQ approach on ―Selenium Exceptions
Guide‖ is a nice one too. In conclusion, I highly recommend this book
for all those aspirants who want to make it big in test automation.

- Mukesh Adhvaryu

xviii

Author Copy. Not For Distribution.


Shweta Bhat
Software Test Engineer

6+ years of comprehensive and in-depth experience in Testing


Hands on experience in Tools like HP Quality Centre11, Bugzilla, JIRA
& basic knowledge of SQL query writing

Technical Skills
- Testing Tools: HP Quality Centre11, Bugzilla, JIRA, Selenium
- Database : Oracle 11g
- OS: Windows, Linux
- Functional Areas: Web Testing, System Testing, Regression Testing,
Sanity Testing,Optical Network testing &Localization Testing
- Test management activities like, test case designing, test case review,
test execution and test execution status reporting

https://sg.linkedin.com/in/shwetabhat

xix

Author Copy. Not For Distribution.


From Code Reviewer

When Mr. Narayanan Palani told me that he was working on part2 of the
book about Testing, I was very happy to hear it. The importance of open
source tool in the automation testing has been rising in the industry for
years, and there are lot of knowledge sharing happening across the
industry. It just required some way of organising the data, that would
help a beginner to understand the starting point and the point where a
learner should stop, and the experienced one would know where he
stands
When I saw the book I found it as a comprehensive guide & also
serves as a great reference as you go about your testing tasks, it not only
prepares you what to code but also how to code. The book has explained
the framework development in detail. Framework is all about defining
and refining class hierarchies. The framework keeps evolving as the
tester/developer gain experience. The code becomes more maintainable
and readable.
Detailed step by step approach of the book introduces to you to
achieve a good framework. Coding standards, creating automation POC,
details on configuration settings, how–to's and related examples on
Selenium web driver will help you code better i.e. maintainable. The
book also gives an insight on Selenium 3.0. Highlighted section in this
book is about preparing the reader for tackling job interviews. Author has
given a lot of tips & tricks, they would help you get ready to face the
interview, where the actual skills of yours speak.
All the best, happy coding & Testing.

- Shweta

xx

Author Copy. Not For Distribution.


Arrchana Mohan
Software Test Analyst

International Software Testing Qualification Board -ISTQB-BCS


Certified,
Agile Scrum Foundation -EXIN(ASF) Certified.
Arrchana holds good experience in building Automation Suite
Framework for Functional test, TestNG framework extended with
Selenium. Experience in Maven for build Automation, Jenkins for
Continuous Integration, Effectively handling SQL. Sound knowledge and
experience in BDD with Cucumber.

https://www.linkedin.com/in/arrchana-mohan-0b61b8106

xxi

Author Copy. Not For Distribution.


From Automation Framework
Reviewer

Around the World, Test Automation is looming dramatically and has


become an essential part of each project. Open Source tools are more
popular and about 88% of organisation opt open source tools for their
Business. Selenium grows rapidly as many Enterprises increasingly
using Internet based applications. It is the booming stage for Selenium
Test Automation as its going to hike the global market.
So what you are looking for ,Are you a new entrant or Automation
admirer, it's the right stage to invest your time to explore in Test
Automation with Selenium Web driver. The Author has design the book
in such a way that, one can understand more depth about the Test
Automation frameworks, which is what needed in today's market.
The creation of the Framework with Selenium is explained more
precisely with stepwise approach, formulated with appropriate
screenshots. Again designing Test suites are more meaningful for
Automation suits as it contains all feasible test scripts, the author has
demonstrate the concept with clean examples and topping with a scenario
to explain suite skipping. Fair clarification of Parameter properties /
parameterization with different browsers, and configuration settings. The
example code's are explained with relevant facts, so new entrant can
easily understand code, which is again additional positive about this
book.
The concepts like checkbox, locators, list box, alerts, dropdowns,
multiple page handling are blended with clear-cut example. TestNG is
again a testing framework which facilities board range of testing needs.
Annotation and jar files of TestNG are revealed with scenarios.
Such a brilliant book with detail insight about Selenium Test
Automation, Highly recommended and satisfied material for those like to
deep dive in Automation Industry.

-Arrchana Mohan

W
xxii

Author Copy. Not For Distribution.


Dinesh Balaji
Avid reader and test automation enthusiastic. Have extensive experience
working in corporate and start-up world and currently working on
mobile automation projects.
http://simpleexpressions.me/

https://www.linkedin.com/in/dinesh-balaj

xxiii

Author Copy. Not For Distribution.


From Topics Reviewer
of This Book

In this fast paced agile development environment, testing plays a


significant part concerning how soon a product can be tested and with
continuous integration, re-tested.
Gone are those days where you wait for the developer to write the
code and then your team designing test cases and a separate team creates
a test data and also team specifically for making builds. Now the tester
owns most of the responsibility, and should have the best of knowledge
in all software development process and also possess the killer mindset
to break the code.
This book stands out from the rest by giving you the real glimpse of
what major scenarios you come across automation and what best tools
you can use to get your job done. As of today, there are a lot of paid and
open source tools available in the market based on your need and
requirement, but the author has chosen the best to serve the general need
of the audience.
I recommend the book for any manual testers who want to step up
their career as automation tester and who aspires to learn more about
what's the current trend in automation and how they can adopt and apply
the knowledge they gain. This book has succeeded in the way of
simplifying manual testers understand the methodology and approach of
automation.

-Dinesh Balaji

xxiv

Author Copy. Not For Distribution.


Venkatesh VI
12.5 years of demonstrated experience in Software Testing on domain-
specific projects (Investment Banking, Capital Markets)
Have led a test team of 20+ people for a Clearing & Settlement
Corporation with an ability to multi-task within a single-project /
program; Worked as a Project Manager of a QA Team with Onshore +
Offshore mix

https://www.linkedin.com/in/venkatesh-vi-6307259

xxv

Author Copy. Not For Distribution.


From Content Reviewer

If there is a professional certification institutionalized by a QA


organization/body, I would certainly recommend this book for Test
Automation enthusiasts - right from the "Novice" to "Intermediate"
level. This book provides a structured way for any automation
enthusiasts/developers to get a next-level view.
In a way, you are Automation Evangelist. I can see that you have
invested a good amount of time for the benefit of Automation engineers
to venture into developing Selenium-based "Auto Robots". I will
recommend this book to my fellow colleagues.

- Venkatesh VI, Test Manager

xxvi

Author Copy. Not For Distribution.


Dedicated to

Yantroddharaka hanuman and Sree Raghavendra Swamy

Sree Raghavendra Swamy


"Pujyaya Raghavendraya Sathya Dharma Rathayacha
Bajatham Kalpa Vrukshaya Namatham Kamadehnave"
"I worship the esteemed Raghavendra who is the protector of Satya and
Dharma. I salute the esteemed Raghavendra who is like a kalpavriksha. I
bow to Sree Raghavendra who is also like our Kamadhenu.
Kalpavriksha is a divine tree, which is there to fulfill all our wishes.
Kamadhenu, similarly is a wish fulfilling cow. It is also sometimes
referred to as mother of all cows."

xxvii

Author Copy. Not For Distribution.


xxviii

Author Copy. Not For Distribution.


Content List

S. no. Content Page no.


1. How to read this book? 1
2. Introduction 3
3. Learner's Study Flow Chart for Selenium 9
WebDriver
4. Download Selenium Projects from GitHub 9
5. Install Java, Eclipse, Cucumber, TestNG 11
 Java Installation 11
 Eclipse Installation 12
 Cucumber Installation 12
 TestNG Installation 13
 Steps to use the existing or ongoing 13
Selenium Automation Project in Eclipse 22
 How to Execute the Scripts from
Automation Framework
6. Automation Test Industry 25
7. Selenium-Brief History 25
8. Why Java based Selenium WebDriver 26
Framework is wide used across the industry?
9. Selenium based Google Search Results prove 28
that Selenium Jobs are most wanted in Testing
Domain
10. Object Capturing Techniques for Automation 32
Testing
11. Selenium Locators 35
 Locating by Identifier 35
 Locating by Id 36
 Locating by name 37
 Locating by XPath 37
 Locating Hyperlinks by Link Text 38
 Locating by DOM 39
 Locating by CSS 40
 Difference between Findelement and 43

xxix

Author Copy. Not For Distribution.


Findelements script? 43
 XPath Examples
12. CMMI Level and Software Testing 45
13. CMMI Level Implementation in Automation 48
Frameworks
 Level 1 – Initial(~ 70%) 49
 Level 2 – Repeatable (~ 15%) 50
 Software Configuration Management 50
 Software Quality Assurance 50
 Software Project Tracking and 50
Overall Status 50
 Software Project Planning 51
 Requirements Management
 Level 3–Defined(< 10%) 51
 Peer Reviews 51
 Intergroup Coordination 52
 Software Product Engineering 52
 Integrated Software Management 53
 Training Program 54
 Organization Process Definition 55
 Organization Process Focus
55
 Level 4–Managed (< 5%) 55
 Software Quality Management(SQM) 55
 Quantitative Process Management 56
 Level 5 – Optimizing (< 1%) 57
 Process Change Management 57
 Technology Change Management 57
(TCM) 57
 Defect Prevention
14. Practice Scripts Sample on Selenium 58
15. How to create a new instance of a browser? 58
16. How to launch a web page using Selenium 60
WebDriver?
17. How to Open a Website using Selenium 60
WebDriver-another example?
18. What happens if your tests are not on the web 60
pages?
19. How to click on a Web Page's button? 60
xxx

Author Copy. Not For Distribution.


20. How to submit a form using Selenium 61
WebDriver-another example?
21. How to send user inputs to web page using 61
Selenium WebDriver?
22. How to handle alerts in Selenium WebDriver? 62
23. How to compare the text presented in the web 63
page with expected texts using Selenium
WebDriver?
24. How to find whether the checkbox selected 64
(or not )using Selenium WebDriver?
25. How to enable or disable a field using 64
Javascript in Selenium WebDriver?
26. How to handle multiple windows when 65
testing a particular page using Selenium
WebDriver?
27. How to click on the sub menu from menu 65
using mouse hovering event in Selenium
WebDriver?
28. How to capture screenshots during Selenium 66
WebDriver Test Execution?
29. How to Identify if the element exist on the 66
page using Selenium WebDriver?
30. How to navigate on WebPages using Back 67
and Forward option of browser?
31. How to select multiple items from the list box 67
using Selenium WebDriver?
32. How to get the Page Title of web page using 68
Selenium WebDriver?
33. How to upload a file using Selenium 68
WebDriver?
34. How to download a file using Selenium 69
WebDriver?
35. How to make the test to wait using Selenium 69
WebDriver?
36. How to get Current web page details? 71
How to generate Alert ? 72
37. How to handle dropdowns in web pages? 73
38. How to understand a dropdown is multi select 75
or single select?

xxxi

Author Copy. Not For Distribution.


39. What is the best way to identify if the object 76
or element present in the web page or not?
40. How to handle multiple web pages within the 77
particular automation test?
41. Selenium 3.o Test Scripting 78
42. Test using Gecko Driver in Selenium 3.0 Beta 79
43. Test using Chrome Driver in Selenium 82
44. Behavior Driven Development and Selenium 84
WebDriver
45. Script to search Google using Selenium 92
WebDriver and JUnit
46. Proof Of Concept(PoC)-Selenium WebDriver 97
Based Test Automation Framework
1. Definition 97
2. Introduction 98
3. Automation PoC approach 98
4.PoC Considerations 98
5. PoC Outcomes 100
6.Assumptions and Dependencies 105
7. Risks Associated 106
8. Problems in Automation 106
9.Methodologies for PoC Approach 106
10.Advantages of PoC 106
11.Entry Criteria 106
12.Exit Criteria 107
13.Test Architecture 107
14. Scripting Guidelines 112
15.Design for Sustainability 113
16.Feasibility Study 113
17.Prove the Concept 114
47. Selenium Web Driver Scripts to build 114
Automation Framework
48. Maintaining Object Repositories and 116
Reusable Components
49. Data Driven Framework -Step by Step 119
Instructions
50. Data Driven Tests using Excel Files with 133
Selenium Web Driver
xxxii

Author Copy. Not For Distribution.


51. Capture Screenshots using Selenium 136
WebDriver
52. How the Screenshot Utility can be extended to 137
Selenium based Framework?
53. XSLT Reporting 139
 Example XSLT report 140
 How to add such XSLT Reports to the 140
emails and send to stakeholders?
54. Parameterization in Automation Framework 142
55. TestNG Scripting for Selenium Automation 144
Framework
 Parallel Test Execution using TestNG 147
TestNG Annotations 148
 DataProvider Annotation in TestNG 153
 TestNG Test Case Priority 154
56. Next Generation Test Automation Results 156
Management
57. Selenium Exceptions Guide 160
 How to handle the tests when 'Server 160
Exception : sessionId should not be null'
occurred?
 How to Handle ERROR: No sessionId 160
provided?
 How to handle 160
UnreachableBrowserException?
 How to handle Illegal state exception 161
using Selenium 3.o beta ?
 How to handle 162
NS_ERROR_FILE_ACCESS_DENIED
in Selenium 3.o?
 How to handle chrome driver issues ? 162
58. Problem Solving Section-Selenium 165
WebDriver
 How to fix a problem when driver throws 165
Null Pointer exception in the code?
 Why there is an POIXML Exception 167
displayed when test data handled from
Excel file?

xxxiii

Author Copy. Not For Distribution.


 How to handle exception of chrome 168
browser when firefox browser is
launched?
 What would be expected when Firefox 168
exception 'Unable to connect to host'
occurred?
 How to execute TestNG based tests in 169
right priority?
 What would be reason why the correct 169
browser driver gives an exception?
 Why TestNG tests fail only in eclipse and 170
works fine in command prompt?
59. Selenium Test Automation Best Practices 171
 Naming Standards in Java based 171
Frameworks
 Function Standards in Java based 172
Frameworks
60. Selenium WebDriver and Ruby based 172
Automation Framework
61. JavaScript based Selenium Cucumber 182
Automation Framework on Linux
62. Selenium IDE Scripts to JMeter Scripts - 186
Performance Testing Techniques
 Pre-Requisites to get Jmeter and Selenium 186
IDE
 Performance Testing Basics 188
63. Advanced Selenium IDE 200
 Steps to Install Additional Plugins 200
 Steps to view Page Coverage using 208
PageCoverage Plugin
 Steps to view Screenshots for the Test 210
Failures using ScreenShotOnFail
64. Automate CRM Applications using Selenium 213
WebDriver Page Object Model (POM)
 Steps to automate the login page 214
 Download Browser Driver for Chrome
Browser
 Introduction of Page Object Model 231

xxxiv

Author Copy. Not For Distribution.


 Advantages of POM based Automation 231
Framework with examples
 Disadvantages of POM based Automation 232
Framework with examples
 How to construct a Simple Page Object 233
Model?
 Page Object Model-A simple alternative 243
method
65. Resume Guide for Selenium Experts 250
66. Resume Evaluation Process for Test 255
Automation Jobs-A Case Study
 Step1: Requirement for the Selenium 255
Automation Tester Role posted online
 Step2-Resume from Candidate 255
 Step3: Resume Evaluation Checklist 258
67. Future of Test Automation Roles or Software 258
Testing Roles
68. Interviews of Selenium Test Automation 261
Roles
 Pre-Interview Project Submission: 261
 Topics on First Technical Round 262
 Topics on Second Technical Round 262
69. Experience of Test Automation 262
 Implementation of Selenium Automation 263
Framework in Agile Projects
 Implementation Stage1 263
 Implementation Stage2 263
 Implementation Stage3 264
70. Why Software Testing is Necessary and 264
Mandatory for Software Projects?
71. Importance of Reliability in Software Testing 266
72. What is Software Testing? 267
73. Why Defects Occur in Software? 268
74. Software Testing-Four Key Objectives 270
75. How Testing and Debugging are different? 271
76. How much Testing is enough? 272
77. Software Testing Principles 272

xxxv

Author Copy. Not For Distribution.


78. Failure Mode and Effects Analysis (FMEA) 276
79. Risk Based Testing 278
80. Migration Strategy from UFT to Selenium 281
 How to migrate the desktop application 282
based UFT (formerly QTP) scripts to
Open Source Tools?
 Few Final words 284
 Appendix A 285
 Appendix B 288
 Appendix C 289
 Appendix D 293
 REFERENCES 296

xxxvi

Author Copy. Not For Distribution.


Table of Figures

S.No. Figure no. Page no.


1. Figure 1 Learner's Study Flow Chart 9
2. Figure 2 Github Signup button 10
3. Figure 3 Github Registration 10
4. Figure 4Github Project Watch and Star 11
5. Figure 5 Github Project Download 13
6. Figure 6 Automation Project Folder 14
7. Figure 7 Eclipse exe file 14
8. Figure 8 Select Workspace in Workspace 15
Launcher
9. Figure 9 Launch Eclipse 16
10. Figure 10 Package Explorer 17
11. Figure 11 Import Existing Project 18
12. Figure 12 Select the project title for Import 19
13. Figure 13 Configure Build Path 19
14. Figure 14 Right Click on Build Path and Choose 20
Configure Build Path
15. Figure 15 Add External JARs 20
16. Figure 16 Verify Added JARs 21
17. Figure 17 Click on Add Library to add relevant 21
JAVA JRE System Library (Java should be
installed as pre-requisite)
18. Figure 18 Add Library Window 22
19. Figure 19 Select Default JRE 22
20. Figure 20 Verify JRE System Library 23
21. Figure 21 Clean Project 24
22. Figure 22 Rus the Tests as TestNG Suite 24
23. Figure 23 Java Class Files 27
24. Figure 24 Programming Jobs as per Indeed.com 28
results listed in codingjobs.com
25. Figure 25 Product Life Cycle based on Google 29
Search Trends

xxxvii

Author Copy. Not For Distribution.


26. Figure 26 Google Search Results Comparison 30
between Selenium
WebDriver,QTP,Ranorex,Watir and Appium
27. Figure 27 Google Search Results Comparison 30
between Ranorex, Watir and Appium
28. Figure 28 Comparison of Google Search Results 31
between Appium,Robotium,Ranorex
29. Figure 29 Google Search Results Comparison 32
between Functional Testing, Penetration Testing,
Performance Testing, Automation Testing and
Android Testing
30. Figure 30 Google Search Results Comparison 33
between Selenium
WebDriver,Appium,JMeter,Manual Testing
31. Figure 31 Inspect Element on Twitter Button of 33
Prezi Page using Google Chrome
32. Figure 32 HTML Code Snippets of the Web Page 33
33. Figure 33 XPath Finder, XPath Checker Add-ons 34
in Firefox
34. Figure 34 View XPath option when right clicked 34
on Twitter Button
35. Figure 35 Clicking on View XPath display the 35
xpath of object
36. Figure 36 XPath Extensions in Chrome Browser 36
37. Figure 37 Right Click on Search Box and Choose 36
Inspect Element
38. Figure 38 HTML Code Snippet of Search Box 39
39. Figure 39 XPath details available from Right 40
Click View
40. Figure 40 SeleniumHQ Web Page 40
41. Figure 41 Selenium IDE is launched and available 41
in Record Mode
42. Figure 42 Right Click on Go Button 42
43. Figure 43 Verify that Selenium IDE updated the 42
script automatically when Go Button clicked (Left
Click)
44. Figure 44 CSS value for the Object Identification 43
45. Figure 45 Identify CSS from Inspect Element- 49
HTML Code Snippet

xxxviii

Author Copy. Not For Distribution.


46. Figure 46 Emailable Report Generated After the 50
Test Execution
47. Figure 47 Object Repository written in Eclipse 51
48. Figure 48 Parameter Properties and Object 52
Repositories are written in Eclipse and scripts
driven from BDD Cucumber
49. Figure 49 BDD Cucumber Feature files written in 53
Eclipse IDE
50. Figure 50 Image Analysing Tools List 54
51. Figure 51 Complete Automation Test Framework 56
52. Figure 52 Quality Improvement in Automation 57
Framework
53. Figure 53 Image Analyser identify defects from 78
Screenshots
54. Figure 54 Download Selenium 3 Beta version (or 79
any latest version) using Java Programming
55. Figure 55 Download Gecko Driver to run Firefox 80
Browser based Tests using Selenium 3
56. Figure 56 Eclipse IDE Package Explorer View of 82
Scripts
57. Figure 57 Launch Browser Test 82
58. Figure 58 Security Alerts 83
59. Figure 59 Chrome Browser Launched with 83
Extension Details
60. Figure 60 Script to eliminate the extension popup 84
61. Figure 61 Sample BDD Project 86
62. Figure 62 Sample Feature File with Gherkin 87
Scripts
63. Figure 63 Step Definitions 91
64. Figure 64 Running the BDD Tests in Cucumber 91
65. Figure 65 Test Execution Started 91
66. Figure 66 Test Execution Results in Output 94
Console
67. Figure 67 Test Results 94
68. Figure 68 Test Results of BDD Feature File 99
69. Figure 69 Sample Page Created using 107
Drive.Google.Com to test the objects
70. Figure 70 Cross Browser Compatibility 108

xxxix

Author Copy. Not For Distribution.


71. Figure 71 Screenshot Capability 109
72. Figure 72 Object Repository 110
73. Figure 73 Parameter Management 111
74. Figure 74 XSLT Reporting Capability 112
75. Figure 75 Logging Capability 119
76. Figure 76 Download Apache POI Files 120
77. Figure 77 Launch Eclipse 120
78. Figure 78 Workspace Launcher 120
79. Figure 79 Create New Java Project 121
80. Figure 80 Create New Java Project 122
81. Figure 81 Configure Build Path 122
82. Figure 82 Java Build Path- Libraries Tab 123
83. Figure 83 Select files from downloaded Apache 123
POI extracted folder
84. Figure 84 Select files from downloaded Apache 124
POI extracted folder
85. Figure 85 Select files from downloaded Apache 124
POI extracted folder
86. Figure 86 JAR files added to libraries 125
87. Figure 87 Create Package 125
88. Figure 88 Create Package 125
89. Figure 89 Crate Class File 126
90. Figure 90 Class File Created 126
91. Figure 91 Import Section 127
92. Figure 92 Excel File Folder Location 127
93. Figure 93 Sheet Name within Excel File 127
94. Figure 94 Data Written in Excel File for the Tests 127
95. Figure 95 Script Location 128
96. Figure 96 Script Location 133
97. Figure 97 Test Execution Results 134
98. Figure 98 Excel Files for the Tests 134
99. Figure 99 Data Input Available from Excel File 134
100. Figure 100 Data to Run Column to write y for Yes 135
and n for No
101. Figure 101 First Row of the Data from Excel File 135
102. Figure 102 Test Output/Results saved to Excel 135
File

xl

Author Copy. Not For Distribution.


103. Figure 103 WriteResult Example 138
104. Figure 104 Screenshots of Passed Tests 138
105. Figure 105 Screenshot of Failed Tests 139
106. Figure 106 Screenshot Folders within Automation 140
Framework
107. Figure 107 XSLT Report 140
108. Figure 108 New Email from MS Outlook 141
109. Figure 109 Locate Test Results (Test Output) 141
Folder
110. Figure 110 Select Test Results File 141
111. Figure 111 Select Insert as Text 142
112. Figure 112 Insert As Text result in adding the 147
HTML Test Results within Email Content
113. Figure 113 Execute the Tests using TestNG 157
114. Figure 114 Download Mogo JAR File and Save in 158
JarFiles Folder
115. Figure 115 Configure Build Path by adding 161
Mongo JAR file
116. Figure 116 IllegalStateException thrown during 161
the test execution
117. Figure 117 Download Latest Gecko Driver to run 163
tests in Firefox Browser when using Selenium 3
onwards
118. Figure 118 Firefox Browser Reference 163
119. Figure 119 Regedit to open Registry Editor 164
120. Figure 120 Firefox Browser's folder within 164
Registry Editor
121. Figure 121 Elements within Registry Editor 164
122. Figure 122 Mozilla Folder 166
123. Figure 123 VerifyPageTitle Code Sample 166
124. Figure 124 Error Screenshot 167
125. Figure 125 BasePage Script 167
126. Figure 126 POIXMLException 167
127. Figure 127 Object Repository in Excel File 168
128. Figure 128 WebDriver Exception 168
129. Figure 129 'Unable to connect to host' Exception 169
during Test Execution (within Output Console)
130. Figure 130 TestNG tests with Priority 170

xli

Author Copy. Not For Distribution.


131. Figure 131 UnsupportedClassVersionError in 170
Output Console
132. Figure 132 Error Description 171
133. Figure 133 TestNG Exception 173
134. Figure 134 New Project Name 174
135. Figure 135 New File 174
136. Figure 136 login_spec.rb file 175
137. Figure 137 Capturing XPath for the Object 175
138. Figure 138 Capturing XPath for the Object 176
139. Figure 139 Capturing Xpath for the Object 176
140. Figure 140 Updating XPath within the Scripts 177
141. Figure 141 Update the URL to test 178
142. Figure 142 Update Development in Environments 181
143. Figure 143 Run the Test 181
144. Figure 144 Test Execution Status 182
145. Figure 145 Test Output 182
146. Figure 146 Test Results 183
147. Figure 147 Feature File 183
148. Figure 148 Step Definition File 185
149. Figure 149 Web Page Designed to Test 187
150. Figure 150 Download Firefox 187
151. Figure 151 Download JMeter 187
152. Figure 152 Add-ons of Firefox Browser 188
153. Figure 153 Downlaod any latest version of 188
Selenium IDE
154. Figure 154 Once Installed, Selenium IDE 190
available as an Icon on top right corner of the
Firefox browser
155. Figure 155 JMeter.bat File 190
156. Figure 156 Test Plan of JMeter 190
157. Figure 157 Add HTTP(s) Test Script Recorder in 191
Workbench of JMeter
158. Figure 158 HTTP(s) Test Script Recorder in 191
Workbench of JMeter
159. Figure 159 Name:Recorder 191
160. Figure 160 Click Start 192
161. Figure 161 Error Notified when Port number 192

xlii

Author Copy. Not For Distribution.


already in use
162. Figure 162 Update Port Number 193
163. Figure 163 Firewall Security Alert-Click on 193
Allow Acces for Java to run the Tests
164. Figure 164 Click OK button for the Certificate 193
165. Figure 165 Tools and Options 194
166. Figure 166 Click Advanced in Options and 195
Choose Network
167. Figure 167 Manual Proxy Configuration 196
168. Figure 168 Selenium IDE and JMeter 196
169. Figure 169 Selenium IDE Scripts 197
170. Figure 170 Recorder 197
171. Figure 171 Recorder (of JMETER) updated with 198
scripts when Selenium IDE scripts are executed
from Selenium IDE
172. Figure 172 Expand JMeter Recorder 198
173. Figure 173 Save Test Plan of JMeter 199
174. Figure 174 Change the Proxy back to 'No Proxy' 206
once the Recording is completed
175. Figure 175 ScreenShot on Fail Add-on for 207
Selenium IDE
176. Figure 176 Page Coverage Add-on for Selenium 207
IDE
177. Figure 177Page Coverage Icon 207
178. Figure 178 ScreenShotOnFail Icon 208
179. Figure 179 Selenium IDE with two add-ons 209
180. Figure 180 View Page Coverage 209
181. Figure 181 Page Coverage Report 210
182. Figure 182 View Failure Report 210
183. Figure 183 Error Report 211
184. Figure 184 Log Search Bar Add-on for Selenium 212
IDE
185. Figure 185 Test Execution Status in Selenium 213
IDE
186. Figure 186 Trailhead Salesforce Page 214
187. Figure 187 Objects of Login Page displayed in 214
Selenium IDE Target Column
188. Figure 188 Show All Available Commands 215

xliii

Author Copy. Not For Distribution.


(Option visible only when Selenium IDE opened
in background)
189. Figure 189 Create New Java Project 216
190. Figure 190 Java Project Name 217
191. Figure 191 Click on Finish Button 218
192. Figure 192 Verify JRE System Library (displayed 219
when Java installed)
193. Figure 193 Package Explorer View 219
194. Figure 194 Jar files from Selenium Installable 220
195. Figure 195 Jar files from Selenium Installable 221
196. Figure 196 Libraries tab within Configure Build 222
Path
197. Figure 197 Create Package 222
198. Figure 198 Create Java Class File 223
199. Figure 199 Name of the Java Class File 223
200. Figure 200 Class File with No Scripts in Early 224
Stage
201. Figure 201 Create Folder 224
202. Figure 202 Browser Drivers 224
203. Figure 203 Code Sample 225
204. Figure 204 Import Details 225
205. Figure 205 Code Sample 226
206. Figure 206 Code Sample 226
207. Figure 207 Code Sample 227
208. Figure 208 Code Sample 227
209. Figure 209 Code Sample 228
210. Figure 210 XPath of Username field 228
211. Figure 211 XPath of Password field 229
212. Figure 212 XPath of Login Button 239
213. Figure 213 Code Sample 230
214. Figure 214 Code Sample 231
215. Figure 215 Run as Java Application 231
216. Figure 216 Console Output 233
217. Figure 217 Create Package 234
218. Figure 218 Create Package and click Finish 235
Button
219. Figure 219 Code Sample 235

xliv

Author Copy. Not For Distribution.


220. Figure 220 Code Sample 235
221. Figure 221 Code Sample 236
222. Figure 222 Code Sample 236
223. Figure 223 Code Sample 237
224. Figure 224 Code Sample 238
225. Figure 225 Code Sample 239
226. Figure 226 Code Sample 239
227. Figure 227 Code Sample 240
228. Figure 228 Code Sample 240
229. Figure 229 Code Sample 241
230. Figure 230 Code Sample 241
231. Figure 231 Code Sample 242
232. Figure 232 Code Sample 243
233. Figure 233 Create Java Package 244
234. Figure 234 Create New Java Class 245
235. Figure 235 Code Sample 245
236. Figure 236 Code Sample 246
237. Figure 237 Code Sample 246
238. Figure 238 Code Sample 247
239. Figure 239 Code Sample 248
240. Figure 240 Code Sample 248
241. Figure 241 Code Sample 249
242. Figure 242 Code Sample 252
243. Figure 243 Type of Profile 259
244. Figure 244 Google Search Results 293
245. Figure 245 Software Automation Testing Secrets 293
Revealed

xlv

Author Copy. Not For Distribution.


xlvi

Author Copy. Not For Distribution.


Selenium Webdriver

How to read this book?

There are two parts associated with Selenium WebDriver reading:


Book1: Software Automation Testing Secrets Revealed
Book2: Software Automation Testing Secrets Revealed Part 2 Selenium
WebDriver
Selenium WebDriver Hands-on Training sessions are recorded (duration:
eleven hours and twelve minutes) and available at following youtube link
in the title "Selenium Test Automation Training Narayanan Palani":
https://www.youtube.com/watch?v=Ke_AQVxMhds
While reading this book the technique of Pomodoro should be followed
thoroughly for better understanding:

Dos:
- Minutely focus your attention for 25 minutes without being
interrupted on any chapter.
- Opt for a breather for 5 minutes to relax your mind. Perform Google
search to analyse your area of difficulty. Then, jot them down on a
paper. (Post these questions in quora.com or stackoverflow.com to
get answered by experts.)
- Write sample code and execute them to analyse results, exceptions or
errors, if occurred any.
- Revise the same chapter at least 4 times in order to strengthen your
concept as more concrete in its approach.
- A 15-minute break is advised to take and then continue reading the
next chapter.
- In case of meeting an alien programming language in the course of
reading, practicing Java programmes using ‗Java BlackBook by
Steven Holzner‘ is duly advised, thereafter, practicing scripts in
command and be prompt to compile and execute.
- Save the practised scripts and get them uploaded to git and be an
‗Open Source Framework Developer‘ at
github.com/narayananpalani/testautomation.

Don’ts:
- Never force yourself to complete the book overnight or within a
week.

Author Copy. Not For Distribution.


Narayanan Palani

- Never plunge yourself to different programming languages until


automation framework has been developed in that language.
- The reading of the chapter and practicing the scripts should not be
performed simultaneously; a comprehensive reading is always
required for a good conceptual understanding of the subject so the
reading should not be a futile attempt; ‗knowing‘ and ‗doing‘ are two
different words.
- In case of meeting an unknown programming language in the course
of reading, practicing Java programmes using ‗Java BlackBook by
Steven Holzner‘ is advised, but practicing scripts in Eclipse or any
IDE while learning those fundamentals is strictly prohibited, as
command prompt gives quick learning in java fundamentals (to
analyse errors) rather than IDEs which help in building the scripts
(whereas Eclipse can be used for Selenium-based learnings).
- The idea like programming language has to be learnt first in order to
start learning Selenium scripting should not be presupposed; both
can be learnt in parallel to understand how the script works for
selenium based tests.

Author Copy. Not For Distribution.


Selenium Webdriver

Introduction
Test automation jobs have been considered as the most wanted in
Information Technology Industry and Selenium WebDriver as one of the
best automation tools in recent years; since the demand of Selenium
WebDriver based jobs are being increased day by bay in the market,
there is always a dire need felt to get test specialists build and maintain
the automation frameworks properly.
But no doubt, there are some challenges and obstructions faced
in the training and development process of new testers (junior testers),
and job seekers are trying various online and face to face selenium
trainings to secure a decent test automation job for themselves. Some of
the training programmes are designed in such a way that high priority is
given to Selenium IDE before getting into Selenium WebDriver training.
Moreover, Selenium IDE is not a best tool to start a training programme
as it is not regarded as the most wanted tool in software test automation;
similarly, there is a lack of certainty on choosing programming
languages in scripting Selenium WebDriver frameworks using Java,
DotNet, Python, Ruby or Javascript. Some training participants first try
their hands on Java until they are hindered by some issues in the code
and then they automatically bounce back to DotNet to continue scripting
which deviates their attention towards failures.
For the purpose of scripting Selenium frameworks and complete
designing of the overall automation framework, it is always strongly
recommended that Selenium learning beginners should be conformed to
one programming language before switching to different languages such
as DotNet; ‗Why Java based Selenium WebDriver Framework is widely
used across the industry?‘ A particular section has been explained in
detail in order to suggest the most suitable programming language to set
about learning the testing frameworks.
Before taking up first few chapters of the book to read, it is
highly recommended to download the entire well-built automation
frameworks from Github-Refer the section ‗Download Selenium Projects
from GitHub‘;
You are suggested to install required software with the help of
the section 'Install Java, Eclipse, Cucumber, TestNG'; these projects will
prove as a great help in the process of running the tests in parallel to
learning the new concepts in each chapter. Following two chapters will
suggest right steps to run such tests in Eclipse:

Author Copy. Not For Distribution.


Narayanan Palani

Steps to use the existing or ongoing Selenium Automation


Project in Eclipse

How to execute the scripts from Automation Framework


When junior testers start off as functional/manual testers, there is a scope
to learn fundamentals of software testing. On the contrary, junior
automation testers have limited scope on the understandings around
testing fundamentals and most of the productivity contribution is only
directed towards test scripting; hence, learning software-testing
fundamentals from project experience is one of the primary needs
required by automation testers, and these examples and basic concepts
can be referred in the chapters below:
- Why Software Testing is Necessary and Mandatory for Software
Projects?
- Importance of Reliability in Software Testing
- What is Software Testing?
- Why Defects Occur in Software?
- Software Testing-Four Key Objectives
- How Testing and Debugging are different?
- How much Testing is enough?
- Software Testing Principles
- Failure Mode and Effects Analysis (FMEA)
- Risk Based Testing

When job seekers complete their Selenium training and are ready to
apply for jobs, most of the CVs fail to match the requirements posted for
the available jobs. This has been regularized as the routine issue for
recruiters to compare each profile to select the best CV. Even job seekers
strive to overcome the hurdles to differentiate CV, resume, bio-data from
one another, while applying for technical roles; in order to suggest right
guidelines for posting the perfect resume on automation jobs, following
sections are to be referred thoroughly:
 Automation Test Industry
 Selenium-Brief History
 Why Java based Selenium WebDriver Framework is widely used
across the industry?
 Resume Guide for Selenium Experts
 Resume Evaluation Process for Test Automation Jobs-A Case Study
Step1: Requirement for the Selenium Automation Tester Role posted
online

Author Copy. Not For Distribution.


Selenium Webdriver

Step2:Resume from Candidate


Step3: Resume Evaluation Checklist
 Future of Test Automation Roles or Software Testing Roles
 Interviews of Selenium Test Automation Roles
 Experience of Test Automation
 Implementation of Selenium Automation Framework in Agile
Projects
Before embarking on the project to write an actual automation
framework, test specialist has to perform a Proof of Concept to validate
whether the tool selection of Selenium WebDriver (using Java) is right
and adds value to the project by increasing Return on Investment; both
this Proof of Concept and respective templates vary based on
organizations but the steps followed within PoC of Automation
Frameworks are identical and it can be analysed successfully using the
chapters below:

Proof of Concept (PoC)-Selenium WebDriver Based Test


Automation Framework
1. Definition
2. Introduction
3. Automation PoC approach
4. PoC Considerations
5. PoC Outcomes
6. Assumptions and Dependencies
7. Risks Associated
8. Problems in Automation
9. Methodologies for PoC Approach
10. Advantages of PoC
11. Entry Criteria
12. Exit Criteria
13. Test Architecture
14. Scripting Guidelines
15. Design for Sustainability
16. Feasibility Study
17. Prove the Concept
When PoC is conducted, test specialist has to figure out the ways of
scripting on Selenium WebDriver (using Java) for various testing needs.
Following chapter will assist in the process of analysing such practice
scripts in Selenium WebDriver with multiple examples:
 Practice Scripts Sample on Selenium

Author Copy. Not For Distribution.


Narayanan Palani

 Selenium 3.o Test Scripting


 Test using Gecko Driver in Selenium 3.0 Beta
 Test using Chrome Driver in Selenium 3.o
 Behavior Driven Development and Selenium WebDriver
 Script to search Google using Selenium WebDriver and JUnit
During Selenium WebDriver scripting, it has been noticed that one
of the primary elements of scripting is Xpath and capturing such Xpath
properties had never been a smooth landing for any job seekers and
especially complex for someone joining from non-I.T background to I.T
jobs; So there are some sections provided with detail and necessary
screenshots to help analysing and understand Xpath capturing logics in
the chapters below:
 Object Capturing Techniques for Automation Testing
 Selenium Locators
 Locating by Identifier
 Locating by Id
 Locating by name
 Locating by XPath
 Locating Hyperlinks by Link Text
 Locating by DOM
 Locating by CSS
In the process of describing automation framework design methods,
many training programmes of Selenium WebDriver fail to achieve the
desired results. To learn and perform Automation Framework Design in
test automation (using Java) for any novice candidate from scratch is
highly important in their course of learning. Scripting few lines of code
in Selenium is not enough to help job seekers in such cases as candidate
is required to be in a position to explain the complete architecture of
automation frameworks with all mandatory features associated with the
framework while building them using Java; So the complete scripts of
automation framework has been uploaded and made available online at
GITHUB (URL given in first few chapters) and the detailed explanations
are provided in chapters below:
 Selenium Web Driver Scripts to build Automation Framework
 Maintaining Object Repositories and Reusable Components
 Data Driven Tests using Excel Files with Selenium Web Driver
 Capture Screenshots using Selenium WebDriver
 How the Screenshot Utility can be extended to Selenium based
Framework?

Author Copy. Not For Distribution.


Selenium Webdriver

 XSLT Reporting
 Example XSLT report
 How to add such XSLT Reports to the emails and send to
stakeholders?
 Parameterization in Automation Framework
 TestNG Scripting for Selenium Automation Framework
 Next Generation Test Automation Results Management
Note: Installation and configuration of each jar files and respective
automation framework features are explained in detail as part of Part1 of
this book
The next big challenge put forward to the test team, while
implementing the automation frameworks in the testing projects, are
from Maintenance and Defect Prevention on such automation
frameworks over the period; The failure to run the tests by automation
frameworks due to configuration changes is an immensely challenging
task. In such cases, CMM Levels have been considered as the most
suggested implementation on test automation projects and the detailed
guidelines pertaining to this are given in the following chapters:
 CMMI Level and Software Testing
 CMMI Level Implementation in Automation Frameworks
While working as test automation specialists, various obstructions
have been faced in automation framework code and test run of various
scripts in the form of exceptions, failures and different issues; These
exceptions are to be addressed with high importance to run the ongoing
tests, failing in which, it impacts the overall test execution schedule; In
such circumstances, the test engineers are to refer stack overflow, Quora
or blogs to find right answers and risk mitigation steps to overcome
Selenium Framework based issues; But some of the latest challenges,
exceptions have been left unresolved and these common questions/
challenges/exceptions are detailed and answered in following chapters to
benefit automation test specialists:
 Selenium Exceptions Guide
 Problem Solving Section-Selenium WebDriver
The best practices on writing Selenium WebDriver based
frameworks are minutely explained in detail in the chapter below:
 Selenium Test Automation Best Practices
Selenium 3 based test scripting and supported browser versions are
detailed in the section below:
 Selenium 3.0 Test Scripting

Author Copy. Not For Distribution.


Narayanan Palani

Behaviour Driven Development has been noted as the most suggested


ATDD (Acceptance Testing Driven Development) method in testing
industry. It is explained in the chapter below:
 Behaviour Driven Development and Selenium WebDriver
After being confirmed of the comfortablity in writing java based
Selenium WebDriver automation frameworks by the test specialists, it is
important to understand the way in which the other scripting languages
are used to script Selenium WebDriver, and these frameworks are
explained in following chapters:
 Selenium WebDriver and Ruby based Automation Framework
 JavaScript based Selenium Cucumber Automation Framework on
Linux
Note: C#-based scripting has been explained with example scripts and
frameworks as part of Part1 book in the chapter below:
Automation Framework using Selenium WebDriver with DotNet
Build Configuration Tools such as Maven and Ant which are
discussed as part of Part1 book in the chapter below:
 Maven Test Automation
 Run Test.bat for Ant Build

Author Copy. Not For Distribution.


Selenium Webdriver

Learner's Study Flow Chart for Selenium WebDriver

Figure 1 Learner's Study Flow Chart

Download Selenium Projects from GitHub


As a pre-requisite before getting into the chapters based learning of
Selenium Implementation, it is strongly advised to make use of well built
automation test projects made available online at
http://github.com/narayananpalani/testautomation

Author Copy. Not For Distribution.


Narayanan Palani

Once page is opened, click on Signup to register on GitHub page:

Figure 1 Github Signup button

Enter relevant details on GitHub registration to create user id and


password:

Figure 2 Github Registration

Once logged onto GitHub page, click on WATCH and STAR to


make sure you are following the project updates; When new projects are
added to the repository, 'watch'ed user ids get notified on the changes:

Figure 3Github Project Watch and Star


10

Author Copy. Not For Distribution.


Selenium Webdriver

Click on Clone or download and choose Download ZIP to download the


entire Automation Frameworks:

Figure 4 Github Project Download

Alternatively, this git project can be cloned and performed Git Pull
Action to update your local repository with up-to-date scripts.
Once projects are downloaded, there are four tools required to access the
automation frameworks and below section help in downloading and
configuring such tools.

Install Java, Eclipse, Cucumber, TestNG


Java Installation
Java programming is a famous and important programming
language in testing industry and testers with Java knowledge are paid
high in the job markets!

Please download java from following link:


http://www.oracle.com/technetwork/java/javase/downloads/index.html

How to understand whether the Java is installed in the computer or


not?
Once the exe file has been downloaded from the website, double click on
the exe file and run the installation of the JAVA program in the
computer. Once it is completed, kindly check the C:/ Drive's Program
Files folder. This folder should have 'JAVA' folder with JDK and JRE
sub folders. Once these folders are displayed in the computer, it means
that the Java installation is completed but the configuration has to be
done to make sure that the JAVA files are identified by the computer.
JAVA Configuration:
Once Java has been installed successfully, JAVA_HOME and PATH has
to be set up in the system as follows:
Right click on 'This PC' and select Properties.

11

Author Copy. Not For Distribution.


Narayanan Palani

Alternatively Navigate to Control Panel and select Advanced


System Settings. In Advanced Tab, click on Environment Variables:
Click on New button and enter the location of JDK folder.
Note: Based on your Java version, the folder name differ. It is better to
navigate to the location and copy the path as below:
Similarly click on the New button again to enter path as follows:
Note: Make sure that you have mentioned the path including bin folder
as above. You can take a copy of this path just by clicking on the bin
folder as below

Why JAVA_HOME and PATH has been updated in Environment


Variable:
Whenever the java programs compiled and executed in computer,
required JAVA files has to be referred during compilation and execution.
So the computer need to know where the JAVA files located and what is
the respective PATH of bin folder. So the file location is provided
through JAVA_HOME and bin folder location is provided through
PATH set up. Once it is completed, it is a good practice to restart
computer and check the version of JAVA through Command Prompt.
Simply running the command JAVA -VERSION will provide the java
version in command prompt which proves that the JAVA installation has
been completed successfully.
Alternative way to set up JAVA_HOME and PATH is through
Command Prompt. This can be done by launching Command Prompt as
follows.
Step1: Press Windows+R (to open RUN)
Step2: Type CMD,Press Enter
Step3: In Command Prompt, Type' SET JAVA_HOME = c:/Program
Files/Java'
Step4: Type 'SET PATH = %PATH%;%JAVA_HOME%\bin'

Once JAVA Installation and configuration has been completed, it is


required to install Eclipse as it act as a tool to write JAVA codes!

 Eclipse Installation
Download latest eclipse version from http://eclipse.org/downloads/
Once downloaded, please install it and open Eclipse from the location it
is downloaded by clicking on eclipse.exe

 Cucumber Installation
Install the Cucumber Plug-in into Eclipse
12

Author Copy. Not For Distribution.


Selenium Webdriver

This plug in enables certain features in Eclipse – e.g. a nice green


cucumber icon for feature files. Also when you double click on a feature
file then it will open the feature in Eclipse rather than opening notepad.
In Eclipse, go to help->install new software

Paste the URL:


http://cucumber.github.com/cucumber-eclipse/update-site
into the ‗Work with‘ text box. Press enter once you have pasted the link
in. Note that if running behind a proxy server and you get a ‗HTTP
Proxy Authentication Required‘ error you may need to contact a system
administrator to set up your proxy server settings.
See http://stackoverflow.com/questions/1940984/how-to-specify-eclipse-
proxy-authentication-credentials
Click the Cucumber Eclipse Plug-in checkbox and hit next, next, accept
the licence agreement and finish

 TestNG Installation
Follow steps:
1. Click on Help > Install New software
2. Add the link http://beust.com/eclipse in Work with text box
3. TestNG feature will be shown, expand the tree node then verify the
version.
4. Tick the check box of TestNG
5. Click on Next button then Finish button.

Steps to use the existing or ongoing Selenium Automation Project in Eclipse

Step1:
Place the AutomationFramework folder in C: Drive like this:

Figure 5 Automation Project Folder

13

Author Copy. Not For Distribution.


Narayanan Palani

Step2:
Launch Eclipse from the folder where it has been installed (Unlike other
software applications, eclipse needed to be launched by exe every time to
open and access where as other software's available in shortcuts or
different links to access while launching them)
Open eclipse.exe (preferable Eclipse Luna):

Figure 6 Eclipse exe file

Step3:
Choose the folder of the automation framework folder and click on OK
button:

Figure 7 Select Workspace in Workspace Launcher

14

Author Copy. Not For Distribution.


Selenium Webdriver

Eclipse Luna launches the screen:

Figure 8 Launch Eclipse

Once opened Click on Workbench button and navigate to the workbench,


Right click on the package explorer and choose Import:

15

Author Copy. Not For Distribution.


Narayanan Palani

Figure 9 Package Explorer

16

Author Copy. Not For Distribution.


Selenium Webdriver

Choose Existing Project:

Figure 10 Import Existing Project

Click on the Browse button to choose the project and select both the
checkboxes to search and copy the existing projects. Choose SAF project
in the list and click on OK Button:

17

Author Copy. Not For Distribution.


Narayanan Palani

Figure 11 Select the project title for Import

Once the SAF project is visible in Package Explorer, navigate to


Configure Build Path as below:

18

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 12 Configure Build Path

Right click on the folder SAF, click on Build Path and click on
Configure Build Path as follows:

Figure 13 Right Click on Build Path and


Choose Configure Build Path

In Properties of SAF,click on the Libraries tab,click on Add External


JARs button as follows:
Note: Make sure that the Libraries tab is clicked and then Add External
JARs button is clicked from there.

19

Author Copy. Not For Distribution.


Narayanan Palani

Figure 14 Add External JARs


(Follow the same steps which are mentioned in this section to add all the
external JARs)

Please select JAR files from JarFiles folder of the project and click
Open to list the jar files within 'Libraries'. If there are existing JAR files
with incorrect path or highlighted with errors, remove them and add fresh
files from JarFiles folder.

Figure 15 Verify Added JARs

Similarly if JRE System Library exists, that is good to run the test in
java based framework; If JRE System Library doesn't appear in the
Libraries above, click on 'Add Libraries' in the Libraries section, and
choose the default JRE (respective version display as third check box)
and click Next and Finish buttons to display JRE System Library.

20

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 16 Click on Add Library to add relevant JAVA JRE System


Library (Java should be installed as pre-requisite)

Select JRE System Library and click Next button:

Figure 17 Add Library Window

Click on Workspace default JRE or any relevant option of Java


installation details (as per your target machine) and click on Finish:

21

Author Copy. Not For Distribution.


Narayanan Palani

Figure 18 Select Default JRE

Once JRE System Library is added without any errors, it will be


listed in Libraries section of Build Path; Right click on Java project--
>Build Patch-->Configure Build Path-->Libraries to validate:

Figure 19 Verify JRE System Library

How to Execute the Scripts from Automation Framework


Click on Project--> Clean

22

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 20 Clean Project

Click on Build Automatically or Build All (If it is enabled)


Now the project should be ready to execute.

Note: Where to start the execution?: Step ' Test Execution through
TestNG' in this chapter
SAF-->testoutput folder-->testng.xml file-->Right click-->Run As--
>TestNG Suite

23

Author Copy. Not For Distribution.


Narayanan Palani

Figure 21 Rus the Tests as TestNG Suite

Where to start editing the scripts?:


Navigate to SAF-->src-->com.stta.SuiteOne-->The Java Files where the
scripts needed to be updated.

Figure 22 Java Class Files

What should be the first step to review the code?


Start looking at param.properties for the URL and SuiteOneCaseOne for
the navigation of the webpage while testing.

References:
 What if there is an error while installing and configuring the
selenium project in Eclipse?
http://stackoverflow.com/questions/2638016/why-no-projects-found-
to-import
24

Author Copy. Not For Distribution.


Selenium Webdriver

 How to setup?
http://www.assertselenium.com/eclipse-2/how-to-setup-a-
WebDriver-project-in-eclipse/
http://stackoverflow.com/questions/18492668/how-to-execute-a-
selenium-test-in-java

Automation Test Industry


Software Testing Industry has evolved from manual to automation tests
and most of the I.T market has been occupied by licensed software's such
as HP's QTP (later changed to UFT), Win Runner, Silk Test, Rational
Robot and Rational Functional Test etc. Every organization has to
confront the challenge in maintaining the overall licenses due to huge
expenses made in different license models which creates an undesirable
affect on the project expenses, hence, a thought has been given over on
this matter to search some of the alternatives to inaugurate own
automation tools to diminish or cut such license cost in the near future.
Top software engineering companies have taken their step ahead in
designing their own automation frameworks and in trying to replace the
licensed automation engines.

Challenges:
Designed with limited features, the newly built automation test
frameworks will have to evolve for some years to engage itself in the
competition against automation tools. By introducing such custom built
automation frameworks, it is indispensable to maintain development and
testing teams for such custom built automation tools.

Selenium-Brief History
JavaScriptTestRunner (later renamed to Selenium), one of the fine
initiative of ThoughtWorks, Chicago has been built by Jason Huggins,
Paul Gross and Jie Tina in initial days; Though the tool has been brought
to view to various technology experts in Demo sessions, but it is not yet
released as an open source release to public worldwide; There was a
possibility to expand this model to script in any language in 'driven'
mode after Paul Hammant took the initiative of open source release
(hence the tool works as an engine in order to interact with the clients in
various different languages while performing the test actions).

 Selenium RC:
Now Selenium has been undergone to better design process but it still
needs browser accessibility using a browser driver, hence, a particular

25

Author Copy. Not For Distribution.


Narayanan Palani

browser is compatible enough to run the test and validate the test steps;
Dan Fabulich and Nelson Spoul from Bea bundled the browser driver
into a standalone server, Selenium RC (Remote Control); Now the script
can work as a server to interact with browser driver scripts but this
requires a stable release, hence, tester can avoid/reduce the test engine
failures in recognising objects of test elements. The trio of Pat
Lightbody, Nelson and Dan have worked on this problem and have come
up with a stabilized version of Selenium RC!

 Selenium IDE:
"UI Element" extension of selenium has been developed by Haw-Bin
Chain in Chicago, and then, it has been invited to merge into Selenium
IDE.

 Selenium WebDriver:
'WebDriver', being a different tool and brainchild of Simon Stewart, was
later merged to Selenium 2.0 hence it is called Selenium WebDriver.

 Selenium Server:
Browsers, which are completely driven by the core scripts from
Selenium Server, communicate to clients through respective browsers.
So hereby you are requested to configure the Selenium Server at start up
by launching command line and to use the command given: java -jar
selenium-server.jar -h
The set of the scripts submitted by the clients (through IDEs such as
Eclipse) in the form of commands sent, are interpreted by server to drive
the browser and test the application and send back the results to the
client.

Why Java based Selenium WebDriver Framework is wide used


across the industry?
Comparing to C#-based automation frameworks of Selenium WebDriver,
Java based framework has been widely accepted and practiced across
multiple test projects. This section explains the primary reasons and
justifications on why any beginner has to begin with java-based
framework rather than C#, python, java script (which is different from
java) and ruby?

26

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 23 Programming Jobs as per Indeed.com


results listed in codingjobs.com

Languages are ranked by available programming job openings for each


language-SQL leading the competition as no.1 programming language
followed by Java.

Reference:
 http://www.codingdojo.com/blog/9-most-in-demand-programming-
languages-of-2016/

While celebrating 20th year of Java programming, it is important to


know that at least 9 million I.T professionals use Java, and on the other
hand, at least 7 billion devices are running in Java programs. It is also
compatible to the earlier versions and offers a support to some strong
companies across the world, hence, it has been placed among the wide
accepted programming languages in software industry.
Hence, it is easy to get access to java resources for Selenium-based
Automation Frameworks and Industry and the best practices can be
applied to maintain the automation frameworks with available cutting
edge technologies.
Especially the software test engineers who start with java-based
automation frameworks have a high probability of securing job than the
other programming languages; After performing a detailed study, it has
been found that test specialist with Ruby background receives less
number of job opportunities which is entirely opposite in the case of
Java-based test engineers, as most of the job opportunity highlight the
requirement of java as a key programming language for automation

27

Author Copy. Not For Distribution.


Narayanan Palani

testers. So it is indispensable to understand Selenium and figure out the


way to design an Automation Framework using Java programming on
Selenium WebDriver.

Selenium based Google Search Results prove that Selenium Jobs are
most wanted in Testing Domain
Let us watch Google Search Patterns on the most wanted test automation
tools:

Figure 24 Product Life Cycle based


on Google Search Trends

Based on number of people search about particular test automation


tools, approximate figures can be compared in the diagram above which
is similar to Industry Life Cycle of Products.
When people search for particular automation tool it can be due to
job availability, product needs, changes within projects to use new tools
and need for a industry wide famous tools to be implemented hence it is
worth watching closely on top testing tools being searched in recent
years.
Top five test automation tools are picked and checked on the google
search patten based on number of people searched each tool in the last
few years time (through google trends) and observed that QTP (renamed
to UFT) which is Quick Test Professional being market leader in
automation testing for a decade and overtaken by Selenium Searches
during Nov'2015. This is also possible due to the latest name Unified
Functional Testing has been wide used rather than the former name QTP.

28

Author Copy. Not For Distribution.


Selenium Webdriver

Nevertheless there is an incremental google searches on Selenium and it


overtakes other famous tools from 2015 onwards;
Interpretation:
QTP can be identified in Stage4 (Decline) where as Selenium can be
identified in Stage2(Development/Growth)
Ranorex, Watir, Appium can be considered as 'initial' stage (Market
Development) of product life cycle.
Google Search Trends:

Figure 25 Google Search Results Comparison between Selenium


WebDriver,QTP,Ranorex,Watir and Appium

When Ranorex,Watir,Appium are considered for comparison, there


is a huge google search trend for appium from the year 2013 which
overtakes Ranorex and Watir in recent years:

29

Author Copy. Not For Distribution.


Narayanan Palani

Figure 26 Google Search Results Comparison between


Ranorex, Watir and Appium

If mobile automation tools are segregated to search only for appium,


robotium, ranorex based search trends, appium being no.1 and steadily
increased in market development where as robotium prove a strong
increment of market and there is a slow growth for ranorex due to
downfall of market development in 2015 as per the Google trends:

Figure 27 Comparison of Google Search Results between


Appium,Robotium,Ranorex

Following testing domains are picked to compare in next level google


trends comparison:
 Functional Testing

30

Author Copy. Not For Distribution.


Selenium Webdriver

 Penetration Testing
 Performance Testing
 Automation Testing
 Android Testing

If testing domains are segregated to evaluate google search trends,


performance testing domain leading the trend as No.1 (declining over a
period of ten years) and closely followed by Automation Testing Domain
(which is in incremental phase) and expected to overtake and reach no.1
position in the next two to three years;Thus Performance Testing can be
considered as Stage4 Decline Stage and Automation Testing Google
Trends can be considered as Stage2 Growth Stage.. Penetration Testing
shows a considerable amount of google searches and being reached to
3rd position, it proves to be an slow incremental phase and it can be
considered as 'Growth' Stage.

Figure 28 Google Search Results Comparison between Functional


Testing, Penetration Testing, Performance Testing, Automation
Testing and Android Testing

When comparing one tool from each domains of testing, Selenium


from Automation Testing based google trends proven to be a sharp
incremental phase and expected to overtake JMeter based google search
trends in two to three years time. JMeter can be considered as a steady
google search trend and Selenium and Appium are searched by more
people from the year 2013. Since Appium is considered in Stage1 Market
Development stage, it will take some more time to pick up the real

31

Author Copy. Not For Distribution.


Narayanan Palani

growth stage where as Selenium reached Stage 2 and steadily growing in


the google search trends.

Figure 29 Google Search Results Comparison between Selenium


WebDriver,Appium,JMeter,Manual Testing

Observations:
JMeter based Performance Test Jobs,Selenium based Automation
Test Jobs are most wanted in the industry where as knowing Appium is
an added advantage for the next ten years and it will be helpful when
Appium reaches the Growth Stage in Google Trends Life Cycle.

References:
 Google. (2016, September 20), Google Trends. Retrieved from
https://www.google.com/trends/

Object Capturing Techniques for Automation Testing


This section explains about how to actually capture an object
details(xpath) to feed into the automation framework; It looks simple and
straight forward but difficult for anyone to start automating first time.
Example:
Navigate to the link:
https://prezi.com/3u00ppzig7i8/test-
automation/?utm_campaign=share&utm_medium=copy
If you want to click on the twitter link and find the object properties,
right click on it and select 'Inspect Element':

32

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 30 Inspect Element on Twitter Button of


Prezi Page using Google Chrome

Clicking on Inspect Element result in a complex html format like the


below and find the object id as 'I':

Figure 31 HTML Code Snippets of the Web Page

Best and easy way to capture object properties using Mozilla Firefox:
Step1: Install Firefox from https://www.mozilla.org/en-GB/firefox/new/
Step2: Launch Firefox->Tools->Addons->Get Add-ons->Choose 'Xpath
Checker' and then 'Xpath finder'

Figure 32 XPath Finder, XPath Checker Add-ons in Firefox

33

Author Copy. Not For Distribution.


Narayanan Palani

Once installed and Firefox is restarted, launch the URL which need to be
tested.
Step3: Right click on the object and choose View Xpath as below:

Figure 33 View XPath option when


right clicked on Twitter Button

Once View Xpath is clicked, object id will be visible to copy:

Figure 34 Clicking on View XPath


display the xpath of object

Update this xpath in the script as below:


driver.findElement(By.id("I")).click();

In Chrome, Add Extensions and select any of the extensions below


which may help in capturing the xpath in easy way:

34

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 35 XPath Extensions in Chrome Browser

How these objects are captured in UFT (formerly QTP)?


'Object Spy' is used within QTP to capture the object xpath elements and
get it updated.

 Selenium Locators
Similar to 'Descriptive Programming' of Unified Functional Testing
(formerly QTP),Selenium scripting required basic knowledge on object
capturing techniques using Xpath. This section will explain the type of
xpath elements and usage guidelines.

 Locating by Identifier
Assuming that 'right click' on the object user id text box and choose
'Inspect Element' result in following html tags:
<html>
<body>
<form id="SigninForm">
<input name="username" type="userID" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
</form>
</body>
<html>

Here userID is the first identifier of the text box: user name hence it
is the Identifier. Using such identifiers will help in running the test
without object identification failures.
So this object can be updated to the script as follows:

35

Author Copy. Not For Distribution.


Narayanan Palani

driver.findElement(By.xpath("//input[@type='userID']"))..sendKeys("Joh
n");
If reusable components are designed then,
driver.findElement(By.type("userID")).sendKeys("John");

 Locating by Id
Instead updating the first identifier, it is always suggested to pick id of
the object across the automation framework; As an example,navigate to
seleniumhq.org web page and identify the properties of the searcb box on
top right corner of the page:
Right click on the search box and click Inspect Element:

Figure 36 Right Click on Search Box


and Choose Inspect Element

Once Inspect Element is clicked ,find the properties in the section below:

Figure 37 HTML Code Snippet of Search Box

<label title="Search SeleniumHQ.org's sites for selenium content"


for="q"></label>
<input type="hidden" value="005991058577830013072:2lr_j6t3fko"
name="cx"></input>
<input type="hidden" value="FORID:" name="cof"></input>
<input id="q" type="text" size="30" accesskey="s" name="q"></input>

36

Author Copy. Not For Distribution.


Selenium Webdriver

<input id="submit" type="submit" value="Go"></input>


</div>
</form
id="searchbox_016909259827549404702:hzru01fldsm"
title="seleniumhq.org Selenium Search"
action="http://www.google.com/cse">
<div>

In the list of properties available in html format, id="q" is the object


id of the search box which is important for testing and get this q to
update the script as below:
driver.findElement(By.id("q")).sendKeys("Selenium 3");

 Locating by name
id="searchbox_016909259827549404702:hzru01fldsm"
title="seleniumhq.org Selenium Search"
action="http://www.google.com/cse">
<div>
<label title="Search SeleniumHQ.org's sites for selenium content"
for="q"></label>
<input type="hidden" value="005991058577830013072:2lr_j6t3fko"
name="cx"></input>
<input type="hidden" value="FORID:" name="cof"></input>
<input id="q" type="text" size="30" accesskey="s" name="q"></input>
<input id="submit" type="submit" value="Go"></input>
</div>
</form
In the list of properties available in html format, name="q" is the object
id of the search box which is important for testing and get this q to
update the script as below:
driver.findElement(By.name("q")).sendKeys("Selenium 3");

 Locating by XPath
In XML documents, XPath is the language used to locate nodes which is
the same name used for automation tests to locate the object XPath. It
can be used to either locate the object element in absolute terms (but not
suggested), or relative to an element that does have an id or name
attribute within xml file.

37

Author Copy. Not For Distribution.


Narayanan Palani

Absolute XPaths contain the exact location of all elements from the root
(html) and as a result are likely to fail during execution with only the
slightest adjustment to the web application.
Find the item with id or name or any nearby object property which less
likely to change in near future and update the script with "//" like the
example below:
Example:
id="searchbox_016909259827549404702:hzru01fldsm"
title="seleniumhq.org Selenium Search"
action="http://www.google.com/cse">
<div>
<label title="Search SeleniumHQ.org's sites for selenium content"
for="q"></label>
<input type="hidden" value="005991058577830013072:2lr_j6t3fko"
name="cx"></input>
<input type="hidden" value="FORID:" name="cof"></input>
<input id="q" type="text" size="30" accesskey="s" name="q"></input>
<input id="submit" type="submit" value="Go"></input>
</div>
</form

In the list of properties available in html format, id="q" is the object


id of the search box which is important for testing and get this q to
update the script as below:
driver.findElement(By.xpath("//input[@id='q']")).sendKeys("Selenium
3");
Alternatively, In the list of properties available in html format,
name="q" is the object id of the search box which is important for testing
and get this q to update the script as below:
driver.findElement(By.xpath("//input[@name='q']")).sendKeys("Seleniu
m 3");

 Locating Hyperlinks by Link Text


Locate the hyperlink from the page and enter the text appeared on the
link as the below:
link=edit this page (for Selenium IDE)
Example-Click on Edit this page link using selenium WebDriver:

38

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 38 XPath details available


from Right Click View

This link can be updated in scripts by,


driver.FindElement(By.LinkText("edit this page")).Click();

 Locating by DOM
Document Object Model shows the way how the document has been
designed as html and it can be updated in scripts by dom=label.
For an example,
<html>
<body>
<form id="signinForm">
<input name="username" type="text" />
<input name="password" type="pwd" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
<html>

In this example dom locator can be ,


dom =document.getElementById('signinForm')
or
dom=document.forms ['signinForm']
or
dom=document.forms [0]

39

Author Copy. Not For Distribution.


Narayanan Palani

 Locating by CSS
Rendering of HTML and XML documents are described in Cascading
Style Sheets known as CSS.
How a selenium beginner understand CSS locator and how to capture
such object property is something explained in the below example:
Launch seleniumhq.org web page in firefox:

Figure 39 SeleniumHQ Web Page

Launch Selenium IDE other side and keep it open:

Figure 40 Selenium IDE is launched and


available in Record Mode

Selenium IDE is opened just to get more command options when the
object is right clicked!
Now right click on the Go button on top right corner:

40

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 41 Right Click on Go Button

Choose any command from the list available and click on it (for
example: choose verifyText id=submit) and then make sure that the
respective code automatically added in selenium IDE as below:

41

Author Copy. Not For Distribution.


Narayanan Palani

Figure 42 Verify that Selenium IDE updated the script


automatically when Go Button clicked (Left Click)

Now click on the dropdown in Target section and there must be list
of xpath options available for the same object which can be chosen
alternatively:

Figure 43 CSS value for the Object Identification

CSS of the Go button is #submit which is taken from this place and it can
be verified from Inspect Element:

42

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 44 Identify CSS from Inspect


Element-HTML Code Snippet

 Difference between Findelement and Findelements script?


This section is suggested by Shweta Bhat, Code Reviewer in order to
utilize right code snippet for selenium scripting.
When findelement script is used, this line of code search for object
on the page, if not present, exception thrown in test output section
(during test execution);
Example code:
driver.findElement(By.id("q")).sendKeys("Selenium 3");

If no object matched on the webpage, it return


NoSuchElementException to the output and tester can identify this line to
get it fixed. In case of one particular match, it executes the script;If there
are more matches, it returns the first appearance of the object in DOM to
the test and run the test.
In case of findelements, if there is no match of object, it returns
empty list to the test and NoSuchElementException displayed in the
output; If one object identified during execution, it returns a list with one
row of object; If many objects matched to ghe element properties, entire
list of values returned to the test execution and tester can control them in
order to perform actions using the test scripts.
Example code:
driver.findElements(By.id("q")).sendKeys("Selenium 3");

 XPath Examples
Examples to update xpath elements in selenium scripts based on
respective object properties:
Object Properties from Xpath to be updated in Selenium
Web Page WebDriver scripts
:submit //*[@submit]
43

Author Copy. Not For Distribution.


Narayanan Palani

:contains("name") //*[contains(text(),"name")]
:disabled //*[@disabled]
:first-child descendant::*[1]
:first-of-type descendant::p[1]
:last-child //*[last()]
:last-of-type //p[last()]
:nth-child(even) //*[(position() mod 2)=0]
:nth-child(n) //*[position() mod n = 1]
:nth-child(odd) //*[(position() mod 2)=1]
:nth-last-child(n) //*[(count() - position()) mod n = 1]
:nth-last-of-type(n) //p[(count() - position()) mod n = 1]
:nth-of-type(n) //p[n]
:only-child //*[count(*)=1]
:only-of-type //p[count(*)=1]
:root /*[1]
:selected //*[@selected]
:text //*[@type="text"]
div > p //div/p
div p //div//p
h1 + div //h1/following-sibling::div
h1 ~ div //h1/following-sibling::*[count(div)]
hasChildNodes //*[count(child::node() ) > 0]
p:not(#enter) //p[not(@id="enter")]
p.me //p[contains(concat(" ", @class, " "),
" me ")]
p[me!="email"] //p[@me!="email"]
p[me*="email"] //p[contains(@me,"email")]
p[me^="email"] //p[starts-with(@me,"email")]
p[me|="email"] //p[starts-
with(@me,concat("email",'-'))]
p[me~="email"] //p[contains(concat(" ",@me, " "),"
email ")]
p[me$="email"] //p[substring(@me,string-
length(@me)-2)="email"]
p#enter //p[@id="enter"]

44

Author Copy. Not For Distribution.


Selenium Webdriver

Reference:
 LAKSHAY SHARMA. (2016, September 10), FindElement and
FindElements Command [Web log post]. Retrieved from
http://toolsqa.com/selenium-WebDriver/findelement-and-
findelements-command/
 Ellie Skobel. (2016, September 10), Selenium Minutes [Web log
post]. Retrieved from http://seleniumminutes.com/

CMMI Level and Software Testing


Capability Maturity Model Integration (CMMI) is related to process
improvement over the testing process and CMMI assist in identifying the
weaknesses and strengths towards the processes involved. In order to
address the weakness in testing process of organization, CMMI is getting
implemented to recognize the issues, challenges and threats and then
opportunities are created to improve process as a set of best practices
prescribed by industry standards.

 Why CMMI is famous across the testing teams?


It is highly recommended to use the best practice of industry If
organizations to prove their efficiency and strong reputation over the
high quality deliverable to its clients. If such best practices can be
brought into practise, there must be some scaling factor or controlling
factor to review and assess the implementation level. Hence, CMMI
levels take care of ceaseless review of existing processes implemented in
the organization.
 What makes CMMI special comparing to other process
improvement standards?
CMMI is highly compatible to Quality Improvement Methodologies like
ISO standards, ITIL and Six Sigma. It is important to note that CMMI is
getting improved and evolved frequently to conformed with the latest
industry changes; Implementation of CMMI Level standards to the
organization or the testing team provide good Return on
Investment(ROI) and incremental quality over the period of time.
 How and why CMMI is getting implemented in Software Testing
Teams?
Software Testing Teams produce various documents and test results to
the stakeholders. Implementing CMMI is benefiting such documenting
requirements and standards of implementing each testing activities,
hence, it improves the quality of the performance of software tests. The
improvement in testing results parallel to the customer satisfaction;
When the customer satisfaction is achieved, consequently it reflects in

45

Author Copy. Not For Distribution.


Narayanan Palani

assisting the testing teams to invest their precious time for planning their
cost saving options on the expenses of the project; CMMI also helps
testing teams to stabilize the high performance delivery and consistent
increment on Return on Investment(ROI).
 Is CMMI all about process improvement only?
CMMI helps in improving the testing process and it can be applied
successfully to testing groups, set of people, rules and teams of different
projects as well.

Choosing right testing specialists for training programs:


Testing teams are required to opt for the proper staff to be trained in
specific testing tools and domain knowledge. CMMI helps in defining
who will be selected and how the testing training programmes can be
utilized to improve the skills and quality of each testing specialist within
the team; hence, it improves the overall quality of the deliverable from
the testing team.

Defining test engineering process groups:


The involvement of multiple test cycles and process engineering
activities has been suggested in case of complex test results being
delivered by the testing team., . In the segregation of test engineering
process groups into different sub groups and in the classification of work
items for evaluation and timely review, CMMI proves to be helpful to
the test managers; By providing the right directions to overcome the
hurdles, CMMI Consultants assist testing teams in every challenges
placed on its way.

Tool Selection:
Testing teams use tools for Requirements Gathering, Defect Tracking,
Test Execution, Configuration Management and many other testing
activities. CMMI performs a major role in this tool selection process and
provides quality standards to identify and select the right tool for the
testing activities.

Evaluation and Improvement of CMMI process implementation:


In case of organization implementing CMMI to testing teams as an
initiative, few selective projects can be selected and CMMI can be
introduced in phase by phase approach. It can extend to rest of the
projects and help improving the overall organization's CMMI level, only
after the submission of customer feedbacks on the implementation.

46

Author Copy. Not For Distribution.


Selenium Webdriver

CMMI Staged Process for Testing Teams:


Level1 Initialized-'Process is unpredictable, poorly controlled and
reactive':
Organizations poses Level 1 of CMMI may have no formalized testing
process and only few projects may hold valid test metrics and review
documentations which have to be improved by following Level2 norms
of CMMI.
Example: No proper Standard Test Plan Template has been followed
across the organization AB Ltd. Though one particular testing team has
been involved in providing high quality test plan but it is not appropriate
for the entire organization to believe that they follow some standards, as
even rest of the teams has to improve their test plan activities to the
required standard.
Level2 Managed-'Process is defined by project and reactive':
Few testing teams are identified and implemented with industry‘s best
practices on requirements gathering, configuration, test project
monitoring and controlling, test design, test execution, defect tracking-
when proven with positive customer feedbacks, these implementation
steps are followed across similar projects which are not having such
quality test activities.
Level3 Defined-'Process is defined for the organization and
proactive':
If CMMI level standards on multiple testing projects are being
implemented by the organization, getting the common organization wise
standards has prescribed as the next level to follow deliverable quality as
per the Level 3 definitions of CMMI. It will help across the projects to
follow one set of regulations and easy to review and evaluate the
organization's quality and target to reach next level of CMMI.
Case Study:
Though AB Ltd has eighteen projects implemented with CMMI
level2 standards, but two projects follow their own standards due to the
unavailability of organization-wise standards. When Level3 is
implemented, AB Ltd releases Test Plan Templates and Defect Tracking
Regulations on what needs to be provided when a defect is raised for
further investigation. This helps the entire organization staff to follow the
standards and improve the quality of test plans and defect tracking
system.
Level4 Quantitatively Managed-'Process is quantitatively measured
and controlled':
Organizations carefully define, collect and review the measurements of
testing teams in this level of CMMI.

47

Author Copy. Not For Distribution.


Narayanan Palani

Example:
AB Ltd has implemented companywide standards on defect raising
standards and followed across the testing teams. But it has been delayed
in getting the defects fixed and retested. This is definite to create
negative feedback from customers so organization has decided to take
control of the defect fix duration. So the list of defects has been raised
and the defect fixing dates have been evaluated and analysed at the same
time to comprehend the reason behind such delays experienced and what
preventive measures can be formulated to avoid such delays.
Level5 Optimized-'Process is focused on continuous improvement':
After the collection and review of the measurements as part of Level 4,
the innovative solutions and technologies are being implemented in
organization to avoid the delays in the project and also to overcome the
challenges within the testing teams.

Case Study:
AB Ltd identified that there are at least 80% of the defects which are
consuming four man-days to fix the bugs and another two man-days for
defect retests. So it consumes at least six man-days to close a bug since
the date it has been raised. AB Ltd puts forward a demand to get these
defects be fixed and retested within two man-days, hence, organization
introduced the defect managers in each testing projects who control and
assign the defects to right developers and get them fixed on time on the
same day or the next. The responsibility of defect retest to get completed
within eight hours post fix and deployment to testing environment is
being rested upon the defect managers. Hence, AB Ltd achieves highest
quality improvement by implementing Level 5 of CMMI standards.
 What CMMI means for Automation Testing World?
Test Managers introduce Automation Frameworks with most of the tests
converted to automated scheduled tests as an Innovation and 'Solution' to
overcome long-term expenses and resource need. This helps in reducing
the number of testers working in projects, reducing overall project
expenditure and increasing comfort over running huge set of tests
multiple times and increased opportunity to find more bugs.

CMMI Level Implementation in Automation Frameworks


When automation scripts are developed, the only motive left is to get the
test cases automated and prove to the business clients that the maximum
tests are automated, and the test scheduled is reduced due to automation
implementation (which is an incorrect approach as implementing
automation is not going to reduce test schedule in a drastic phase); To

48

Author Copy. Not For Distribution.


Selenium Webdriver

focus on better testing has been considered as the real implementation of


test automation rather than reducing the test schedule and resources.
Level 1 – Initial (~ 70%)
Test automation frameworks are developed and implemented in test
projects and most of the projects never concentrate on improving the
frameworks to better quality which results in false positives within the
test results; False positives means that the tests getting executed are
failed most of the times due to automation framework‘s inefficiency
rather than actual functional failures; This kind of test result causes
incorrect understanding of overall test project status.
For example,
Total Tests Executed: 300
Tests Passed: 100
Tests Failed: 200*
Out of 200 test cases, at least 100 were failed due to incorrect
configuration, code within automation framework, hence, pass
percentage of 33% is incorrect in this project and the real pass percentage
must be ranging from 33% to 66% (which can be identified only when
the tests are repeated and identified the real test results)
Example: 2,012 ms (milliseconds) are spent for no reason on
SuiteOneCaseTwo which would have been avoided and it gives incorrect
report structure of skipping 213 tests which are not required in the report:

Figure 45 Emailable Report Generated


After the Test Execution
49

Author Copy. Not For Distribution.


Narayanan Palani

Suggestion: Once the automation frameworks are developed, it has to be


revised with Requirements of CMMI Level2

Level 2 – Repeatable (~ 15%)


 Software Configuration Management
Parameters such as URLs, Screenshots, Browser selections are to be
captured in an exclusive parameter file (refer parameter properties
related sections);
Developed automation framework has to be configured to use
Maven or Ant to build the project and repeat the test executions as a
project build.

Figure 46 Object Repository written in Eclipse


 Software Quality Assurance
Automation scripts are to be reviewed by team which lead and provide
recommendations to amend the code from time to time.
You are instructed to raise bugs related to automation frameworks
in a separate project (dedicated for the framework) and track the defects;
These are the defects of automation scripts which are to be fixed by
testers to get the better quality within the utilization of automation tools.

 Software Project Tracking and Overall Status


You are instructed to configure the project in Jenkins and track, and
thereby, schedule and manage the overall status using Addins within
Jenkins with configurable test reports.

 Software Project Planning


In order to bring the desired improvements in the framework which is
meant to adopt the next level functional requirements, automation
framework's development has to be planned and derived carefully in
'Test Automation Framework Development Plan' with timelines.

50

Author Copy. Not For Distribution.


Selenium Webdriver

 Requirements Management
A framework can handle objects in exclusive object properties file,
similarly, cross browser compatibility, log4j enablement, XSLT
reporting are some of the capabilities within the automation framework
and was once derived by test managers and test leads as a basic
requirement to include in the scripts; Hence, these requirements are to be
managed in a document for further analysis and improvements over a
period of time.

Figure 47 Parameter Properties and Object Repositories are written


in Eclipse and scripts driven from BDD Cucumber

Level 3 – Defined (< 10%)


 Peer Reviews
The main purpose of Peer Reviews is to remove framework-based
defects early and efficiently from the software work products. An
important corollary effect is meant to develop a better understanding of
the test automation products as well as of the defects that might be
prevented.
In every test cycle, Test framework's scripts are to be reviewed by
peers and the changes are to be updated to the latest version of scripts;
These changes can be managed either by GIT or SVN or any relevant
configuration management systemvi.

51

Author Copy. Not For Distribution.


Narayanan Palani

 Intergroup Coordination
When stable automation frameworks/tools are produced, it can be shared
across other teams for different projects by managerial coordination; It
will help in reducing the chances the repeated work of designing brand
new automation frameworks; For example, business analysts can
produce requirements in terms of feature file scenarios rather than SPSD
documents which reduces burden of work for both development and
testing team; These feature files can be reutilized for automation tests of
testing team and used for unit tests by developers as well; Similarly, tests
which are not automated can be executed directly by referring to the
cucumber feature file by functional testing teams.

Figure 48 BDD Cucumber Feature files written in Eclipse IDE


Software Product Engineering
It has been advised to implement advanced product engineering
technologies such as Orthogonal Array based Pair Wise Test
Combinations within Data Driven Automation Framework in order to
reduce the number of repeated or duplicate tests;
Analyse the test results using MongoDB and receive Data Marts of
test results to evaluate overall progress in testing;

52

Author Copy. Not For Distribution.


Selenium Webdriver

Establish automated test result analysers with the help of image


analysing tools such as ImageJ, Cell Profiler, Neuronstudio, VIAS or L-
Studiovii to automatically analyse the test failures or success using
screenshots downloaded as part automated test execution.

Figure 49 Image Analysing Tools List

 Integrated Software Management


When teams make use of different testing tools to cater their needs, they
all can be integrated into a single unique architecture and implemented
across the fresh projects to save time and reduce maintenance work on
the frameworks.

53

Author Copy. Not For Distribution.


Narayanan Palani

Figure 50 Complete Automation Test Framework

 Training Program
The purpose of the Training Program key process area is to develop the
skills and knowledge of testing professionals so that their performance in
their automation roles can be effectively and efficiently madeviii.
It is advisable to pre-plan the formal training on the developed
automation framework before the recruitment process of new resources
to testing teams. Clear documentation on the automation frameworks

54

Author Copy. Not For Distribution.


Selenium Webdriver

along with recorded video sessions of test leads whereas explaining the
automation frameworks would reduce lot of time invested in the training
by testing resources during their tight project timelines;
For example, a new resource has joined in test automation team but
the entire team is undergoing stress due to the last three weeks of project
delivery to the clients; In such circumstances, it is impossible to provide
required training for the new resources and management expected to
make the productivity of resources since the day 1 which is a
contradiction to the plan (as the training itself not provided or
Incomplete); In these project situations, recorded video sessions and
documentations contribute as major advantages on the training plans for
the new resources included in the test automation teams.

 Organization Process Definition


The purpose of Organization Process Definition is to develop and
maintain a usable set of software process assets and reusable components
that improve automation process performance across the projects and
provide a basis for cumulative, long-term benefits to the organization
with better Return on Investmentix.
Note: Refer Part1 of the book to understand the profit-making
calculations on 'Return on Investments'

 Organization Process Focus


Organization Process Focus involves developing and maintaining an
understanding of the organizations‘ and projects‘ software test
automation processes and coordinating the activities to assess, develop,
maintain, and improve these automation processesx.

Level 4 – Managed (< 5%)


 Software Quality Management (SQM)
SQM involves defining quality goals for the automation products,
establishing plans to achieve these goals, and monitoring and adjusting
the automation test plans, software work products, activities and quality
goals to satisfy the needs and desires of the customer and end user for
high quality products to test in project cyclesxi.

55

Author Copy. Not For Distribution.


Narayanan Palani

Figure 51 Quality Improvement in Automation Framework

 Quantitative Process Management


The organization collects process performance data of automation tests
from the software projects using advanced storage systems such as
MongoDB and uses these data to characterize the process capability (i.e.,
the process performance a new testing project can expect to attain) of the
organization's standard software process, which is described in the
Organization Process Definition key process area for test automation
category.
Process capability describes the range of expected results by
following a software automation process (i.e., the most likely outcomes
that are expected from the next testing project the organization
undertakes in near future). These process capability data are, in turn,
used by the testing projects to establish and revise their process
performance goals and to analyse the performance of the projects'
defined software processesxii.

56

Author Copy. Not For Distribution.


Selenium Webdriver

Level 5 – Optimizing (< 1%)


 Process Change Management
PCM involves defining automation test process improvement goals and,
with senior management sponsorship, proactively and systematically
identifying, evaluating and implementing improvements to the
organization's standard automation process and the projects' defined
software processes on a regular basis.
Training and incentive programmes are established to enable and
encourage everyone in the organization to actively participate in
automation process improvement activities. Improvement opportunities
are identified and evaluated for potential payback to the organization
through various demo sessions of new tools in automation. Pilot efforts
are performed to assess process changes before they are incorporated into
normal practice of automation frameworksxiii.

 Technology Change Management (TCM)


TCM involves identifying, selecting, evaluating new technologies, and
incorporating effective technologies into the organization such as
Selenium 3.0 and Image Analysers on Screenshots of Test Results. To
improve software quality, increase productivity and decrease the cycle
time for product testing – have been considered as sole its objective.

Figure 52 Image Analyser identify defects from Screenshots


Defect Prevention
Trends are analysed to track the types of tool and configuration
defects that have been encountered and to identify defects that are likely
to recur in the framework. Based on an understanding of the project's
defined software process and its implementation, the root causes of the

57

Author Copy. Not For Distribution.


Narayanan Palani

defects and the implications of the defects for future activities are
determined for the framework implementation.
Avoiding the defects within test automation framework needs a
continuous monitoring on the scripts to amend and repeat the latest
objects associated with the projects; Also when browsers, operating
systems are upgraded, compatible browsers are to be deployed within
framework immediately to avoid the defects within the framework.

 Practice Scripts Sample on Selenium


Before explaining about the complete automation framework project in
the next sections, it is important to learn few piece of codes and
commands for better understanding on how selenium WebDriver based
scripts are written in JAVA.This section explains commands and
solutions to few very important questions arise in beginners learning
curve.

How to create a new instance of a browser?


Following are the basic line of code to create a new instance of the web
browser; Basically every test execution of scripts need a new browser to
test on particular web page; In order to launch the web page, we need an
exclusive browser and then page can be launched; Also this particular
browser should be consistently connected with Selenium in order to
perform the tests on particular object; So it is required and must to
initiate the new instance of the particular browser through:
If Firefox needed for test:
WebDriver driver = new FirefoxDriver();
Chrome:
WebDriver driver = new ChromeDriver();
Internet Explorer:
WebDriver driver = new InternetExplorerDriver();
As a beginner to selenium tools, if you send instructions only through the
line above, the script will fail stating that the browser is unidentified!
Because the path of the exe should be highlighted within the scripts in set
properties code. It can be done through following sample of chrome
driver script in which please update the path of exe file based on the
location in your (target) machine:
System.setProperty("WebDriver.chrome.driver","E://AutomationPr
oject//Training//SampleJavaSeleniumProj//BrowserDrivers//chromedrive
r.exe");
driver = new ChromeDriver();

58

Author Copy. Not For Distribution.


Selenium Webdriver

Alternative Script:
System.setProperty("WebDriver.chrome.driver",
System.getProperty("user.dir")+"//BrowserDrivers//chromedriver.exe");
driver = new ChromeDriver();

Note: Make sure that ChromeDriver is imported using the code,


import org.openqa.selenium.chrome.ChromeDriver;

Upto Selenium 2 version:


In case of Firefox Driver initiation, only following line of code required
since there is no need of new exe file for firefox in the framework (since
firefox is inbuilt with Selenium):
WebDriver driver = new FirefoxDriver();
Note:
Make sure that FirefoxDriver is imported using the code,
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.firefox.FirefoxProfile;

Selenium 3 onwards:
Gecko driver need to be downloaded and respective path has to be
provided in system set property in order to run the tests in Firefox
browser.
Example:
System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PRO
PERTY,"E://AutomationProject//Training//SFS//BrowserDrivers//gecko
driver.exe");
WebDriver driver = new FirefoxDriver();
Wait<WebDriver> wait=new WebDriverWait(driver,30);
driver.get("http://www.raghava.uk");

Similarly use the below code in case of Internet Explorer:


System.setProperty("WebDriver.ie.driver",
"E://AutomationProject//Training//SampleJavaSeleniumProj//BrowserDr
ivers//IEDriverServer.exe");
driver = new InternetExplorerDriver();

Alternative Script:
System.setProperty("WebDriver.ie.driver",
System.getProperty("user.dir")+"//BrowserDrivers//IEDriverServer.exe";
driver = new InternetExplorerDriver();

59

Author Copy. Not For Distribution.


Narayanan Palani

Note:
Make sure that Internet Explorer Driver is imported using the code,
import org.openqa.selenium.ie.InternetExplorerDriver;

How to launch a web page using Selenium WebDriver?


The first question after initiating browser is on why there are two
different steps followed to initiate and then launch the web page
separately and why won't we launch a page directly from a web page by
yourself? Simply the answer is No -because the test engine has to
understand which browser has to be initiated and what web page is to be
launched. So after performing the web browser initiation, following code
has to be sent to Selenium to perform web page launch event:
driver.get("www.raghava.uk");

How to Open a Website using Selenium WebDriver - another example?


Most of the automation tests of Selenium has to open the web page in
order to test the steps further. Different browsers can be used but tester
should be aware of creating an instance of driver using WebDriver as
below and get the url:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");

What happens if your tests are not on the web pages?


If your tests needed to be performed on applications such as calculator or
any desktop applications, they are not in selenium WebDriver's scope as
the test engine is made to automate primarily on web based tests. Please
use Appium in case of mobile based tests and UFT ,Ranorexxiv or RFTxv
for Application based tests (rather than web tests)

How to click on a Web Page's button?


Capture the ID of the button from the page using xpath checker or xpath
finder addins in firefox, or simply by checking ID by right clicking on
the button and choose' inspect element'; Once ID is identified, update the
below script and execute to validate the button click:
driver.findElement(By.id("submit")).click();

How to store a text from particular object on web page?


String txtDropdown = driver.findElement(By.ID("select")).getText();

60

Author Copy. Not For Distribution.


Selenium Webdriver

How to submit a form using Selenium WebDriver-another example?


Filling a form in an online website is a regular functionality across retail
websites;Registration on a mobile network provider's website need
customer details to be sent through Registration form and user enters
personal details and click on Submit or OK or Save or Proceed button to
proceed further and get the product or services they need. In order to
send user inputs to enter in fields,sendkeys command used;Similarly
submitting a form can be done using click command on the submit
button.
If user intend to enter personal details on the website and click on
Submit button, it can be done through:
/*Note: FirstName034 is the object name on the website, FirstName
is the parameter name which is getting the data input from excel based
data which has column title as FirstName-parameter name in the script
file and the column name of the excel file should match each other hence
script can retain value from excel and feed to web page on the respective
object FirstName034 in few seconds time.*/
driver.findElement(By.xpath("//input[@name='FirstName034']")).sendK
eys("FirstName");
driver.findElement(By.xpath("//input[@name='LastName035']")).sendK
eys("LastName");
driver.findElement(By.xpath("//input[@name='EmailID036']")).sendKey
s("EmailID");
driver.findElement(By.xpath("//input[@name='MobNo037']")).sendKeys
("MobileNumber");
driver.findElement(By.xpath("//input[@name='Company038']")).sendKe
ys("CompanyName");
/*After entering the inputs using senkeys command in the lines
above, use .click to click on submit button in the line below. Also there is
a fair amount of seconds taken by many websites to display submit
button or enable the submit button only when all the details are filled
hence validating all the fields and enabling submit button takes 2 to 4
seconds in a good network where as it takes upto 10 seconds in slow
network of internet. So it is always advicable to have a wait or sleep
command before clicking on submit button*/
Thread.sleep(2000);
driver.findElement(By.xpath("//input[@name='Submit']")).click();

How to send user inputs to web page using Selenium WebDriver?


Most of the web pages are tested by entering specific values in
textfields.This can be done by the command below.

61

Author Copy. Not For Distribution.


Narayanan Palani

driver.findElement(By.xpath("//input[@name='FirstName034']")).sendK
eys("FirstName");
/* FirstName034 refers to the object id captured by xpath identification
techniques (refer the appropriate section to learn how it can be
discovered) and FirstName is the parameter used in the class file and the
name of the column in excel where this details are provided.*/

How to handle alerts in Selenium WebDriver?


At times it is possible that web pages display alerts to users and it can be
anything related to the functionalities; For example, Incorrect
Passwords result in alert messages on top of the web pages and it is easy
capture such messages manually. But this alert has to be captured and
identified using the automation engine and validate the messages
displayed on the alert message during test execution whenever tests are
scheduled; Hence this alert handling mechanism has to be scripted in a
perfect logic to repeat with 100% success rate during test execution.
At times, tester has to capture the text message appear on the alert and
print it in execution logs. It can be done with the following logic:
driver.findElement(By.xpath("//input[@value='OBJECT
NAME']")).click();
/*To locate alert on the web page using the object Alertpopup, please
switch to alert box from web page:*/
Alert Alertpopup = driver.switchTo().alert();
//Read the text present in the alert popup and save it in a string in order to
print it later:
String Alerttext = Alertpopup.getText();
/*Get the text of alert to be printed during execution in test logs so that
tester can verify during run time or after execution*/
System.out.println(Alerttext);
Thread.sleep(2000);
//To accept on alert popup perform accept action:
Alertpopup.accept();
Note: accept() clicks on OK button on an alert popup when displayed; If
the tests are failed due to incorrect object recognition, or timing delays,
please introduce an if loop with wait statement to click on OK button
whenver the popup displayed.

If you are decided to click Cancel instead of OK,please realign the


code as below:
driver.findElement(By.xpath("//input[@value='OBJECT
NAME']")).click();
62

Author Copy. Not For Distribution.


Selenium Webdriver

/*To locate alert on the web page using the object Alertpopup, please
switch to alert box from web page:*/
Alert Alertpopup = driver.switchTo().alert();
//Read the text present in the alert popup and save it in a string in order to
print it later:
String Alerttext = Alertpopup.getText();
/*Get the text of alert to be printed during execution in test logs so that
tester can verify during run time or after execution*/
System.out.println(Alerttext);
Thread.sleep(2000);
// Click Cancel on alert popup perform dismiss action:
Alertpopup.dismiss();

If alert popup request input from user to enter user id once again for
authentication confirmation,that can be done by sending the keys as
below:
driver.findElement(By.xpath("//input[@value='OBJECT
NAME']")).click();
/*To locate alert on the web page using the object Alertpopup, please
switch to alert box from web page:*/
Alert Alertpopup = driver.switchTo().alert();
//Read the text present in the alert popup and save it in a string in order
to print it later:
String Alerttext = Alertpopup.getText();
/*Get the text of alert to be printed during execution in test logs so that
tester can verify during run time or after execution*/
System.out.println(Alerttext);
Alerttext.sendKeys("User123");
Thread.sleep(2000);
//To accept/Click Ok on alert popup perform accept action:
Alertpopup.accept();

How to compare the text presented in the web page with expected
texts using Selenium WebDriver?
During the test execution, certain texts are to be validated; When
customers submit the personal details, some of the websites display form
submission status such as 'thank you for registration' or relevant
messages as described in the Business Specifications. This has to be
validated using assertequals method in selenium WebDriver.
Example:

63

Author Copy. Not For Distribution.


Narayanan Palani

@Test
public void assertion_method () {
Actualtext = driver.findElement(By.xpath("<ObjectID>")).getText();
/*Text from the webpage is saved in Actualtext object and compared in
the below script*/
Assert.assertEquals(Actualtext, "Form Submission Successful");
System.out.print("\n assertion_method execution successful");
}

How to find whether the checkbox selected (or not )using Selenium
WebDriver?
During test execution, certain checkboxes are bydefaulted selected, some
or not.This can be verfied using isSelected command in asserTrue.If
executed, it update pass when checkbox selected,otherwise it fails the
step and stop the test!
@Test
public void asserttrue1() {
System.out.print("\n"+checkbox.isSelected());
Assert.assertTrue(chkbox12.isSelected());
System.out.print("\n asserttrue1 - > Executed - means assertion is
pass");
}

How to enable or disable a field using Javascript in Selenium


WebDriver?
If a webpage allows either to enable or disable a particular field on the
screen, it is important to know respective mechanism to enable or disable
them.
Sample Code:
driver.getElementsByName('<ObjectID>')[0].setAttribute('disabled', '');
driver.getElementsByName('<ObjectID>')[0].removeAttribute('disabled';

Validate the changes to enable the field post update:


boolean ContactNumber =
driver.findElement(By.xpath("//input[@name='<ObjectID>']")).isEnable
d();
System.out.print("\nBefore : <ObjectID> Text box enabled status is :
"+ContactNumber);

64

Author Copy. Not For Distribution.


Selenium Webdriver

Validate the changes to disable the field post update:


boolean ContactNumber =\
driver.findElement(By.xpath("//input[@name='<ObjectID>']")).isDisabl
ed();
System.out.print("\nBefore : <ObjectID> Text box enabled status is :
"+ContactNumber);

How to handle multiple windows when testing a particular page


using Selenium WebDriver?
When a webpage opens another webpage while clicking on the button or
other events, this has to be handled using Selenium WebDriver to switch
to new window and then switch back to earlier window if required.

Import the utility set within the script:


import java.util.Set;

//Use the below command to handle windows within the script:


Set<String> AllWindowHandles = driver.getWindowHandles();
//Have the array model introduced to capture all parent and child
windows expected to be displayed.
String window1 = (String) AllWindowHandles.toArray()[0];
String window2 = (String) AllWindowHandles.toArray()[1];
String window3 = (String) AllWindowHandles.toArray()[2];
String window4 = (String) AllWindowHandles.toArray()[3];
//Use SwithTo commands to switch between the windows to continue
testing
driver.switchTo().window(window2);

How to click on the sub menu from menu using mouse hovering
event in Selenium WebDriver?
When menu bar of the web page has sub menu items, it is difficult to click
on them at times; This is solved by mouse hovering commands where
selenium move the mouse over menu to open sub menu and clicks on the
respecive submenu item as below:
Actions mouse_actions = new Actions(driver);
WebElement mouse_moveonmenu =
driver.findElement(By.xpath("<Object ID>"));
mouse_actions.moveToElement(mouse_moveonmenu);
mouse_actions.perform();

65

Author Copy. Not For Distribution.


Narayanan Palani

How to capture screenshots during Selenium WebDriver Test


Execution?
Capturing screenshots for the test execution is one of the important
script in test automation and this evidence is required for further
investigation on defects checking. This can be done by TakesScreenshot
utility below:
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import java.io.IOException;

@Test
public void sampletest () throws InterruptedException, IOException
{
//Capture entire page screenshot and then store it to destination drive
File snapshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(snapshot, new File("C:\\screenshot.jpg"));
System.out.print("Snapshot is saved in C: Drive");
}

How to Identify if the element exist on the page using Selenium


WebDriver?
In some of the tests, before performing click or enter values operations, it
is important to know whether the element present in the page or not. This
can be done using the below command structure:
@Test
public void sampletest () throws InterruptedException
{
//If the object is changes with suffix id in random:
for (int i=1; i<10; i++)
{

/*When object id is getting changed often on the web page element, it


can be handled with common text identifier. Find a common unchanged
text and mention that in the line below and it will get update to text1 or
text2..text 9 to make sure that the right xpath is identified during the
test*/
String XPath = "//input[@id='text"+i+"']";

66

Author Copy. Not For Distribution.


Selenium Webdriver

//To verify the element exist or not:


Boolean iselementexist =
driver.findElements(By.xpath(XPath)).size()!= 0;
if (iselementexist == true)
{
System.out.print("\nExpected TextBox"+i+" Is Available On The Page");
}
else
{
System.out.print("\nExpected Text Box"+i+" Is Not Available On The
Page");
}
}
}

How to navigate on WebPages using Back and Forward option of


browser?
While performing tests on the browser, it may be required to go back or
go forward to navigate on the browser hence below scripts are used:
driver.navigate().back();
driver.navigate().forward();

How to select multiple items from the list box using Selenium
WebDriver?
When list boxes are designed with multiple user selections, it is easy to
select the items as below:
Use the below line of code to use select user interface within the code:
import org.openqa.selenium.support.ui.Select;

@Test
public void sampletest () throws InterruptedException
{
Select listbox = new Select(driver.findElement(By.xpath("<Object
ID>']")));

/*If the listbox support to select multiple options,find it throw this if


statement and proceed.If it won't support, print message "multiple
selections are not available"*/
if(listbox.isMultiple())
{

67

Author Copy. Not For Distribution.


Narayanan Palani

System.out.print("Multiple selections is available");


//This line of code search for the exact text mentioned in the code and
match to the respective object within the list box:
listbox.selectByVisibleText("First Class");
//This line of code search for the value of the object within the list box as
SecondClass and select it:
listbox.selectByValue("SecondClass");
//This line of code selection the list item based on the index of particular
item:
listbox.selectByIndex(5);
Thread.sleep(3000);
/*Using the below options, tester can deselect the entire list*/
listbox.deselectAll();
Thread.sleep(2000);
}
else
{
System.out.print("multiple selections are not available");
}
}

How to get the Page Title of web page using Selenium WebDriver?
When tester validate particular page, it is good to check the title using
driver.getTitle(); to make sure the text presented as expected and
mentioned as per system specifications.
/*Use the below command and print in the logs to validate the title of the
page */
String pagetitle = driver.getTitle();
System.out.print(pagetitle);

How to upload a file using Selenium WebDriver?


Depends upon the functionality designed on each web page, upload
functionality based test automation has to be realligned; In most of the
complex cases, AutoIT or Sikuli are extended to script and enable the
upload functionality tests.
If the 'upload file based feature' required only filepath and upload
the file based on the user input, it can be implemented using the code
below:

68

Author Copy. Not For Distribution.


Selenium Webdriver

driver.findElement(By.id("uploadnewfile")).sendKeys("E:\AutomationPr
oject\Training\DataDrivenFramework\ExcelFolder\TestInput.xlsx");

How to download a file using Selenium WebDriver?


If the files are provided with links within the webpage to get
downloaded, following code snippet can be used to update the text
available on the link and click to download the file.
driver.findElement(By.xpath("//a[contains(.,'Download
Report')]")).click();
Note:If there is a functionality post download action to click OK or any
windows based actions, AutoIT or Sikuli has to be extended to script the
windows based actions.There is no possibility to handle windows native
dialogues by selenium WebDriver scripts.

Reference:
 Andreas Ebbert-Karroum. (09/07/10), File Downloads With
Selenium - Mission Impossible? [Web log post]. Retrieved from
https://blog.codecentric.de/en/2010/07/file-downloads-with-
selenium-mission-impossible/

How to make the test to wait using Selenium WebDriver?


As a beginner to Selenium WebDriver if you try to search in detail about
types of selenium waits and how they differ from each other, there are lot
of web pages available to explain the differences; But users are getting
confused with those differences and using incorrect wait in the project
result in test failures hence this section is very important and provided
with lot of code samples to understand how the wait usually work for
selenium WebDriver.
There are three types of waits available: Implicit Wait,Explicit
Wait,Fluent Wait
Implicit Wait:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Real Time Challenges:
-This script works for Firefox Browser where as it won't always work for
Chrome and IE kind of browsers hence it is suggested to use Explicit
Wait below.
-If the driver shows the particular object within 2 seconds of time, test
wait for another 8 seconds to match 10 seconds mentioned in the
implicitwait and continue to next step. So this can be avoided using
explicit wait rather than implicitwait methods.

69

Author Copy. Not For Distribution.


Narayanan Palani

Explicit Wait:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xp
ath("//div[@id='<Object ID>']"), "Enter Your Personal Details"));
/*Introduce the instance of WebDriverWait and set the timer for 20
seconds and literally this means, the wait command wait only until the
text getting visible on the object;If the text present in 3 seconds and the
wait completes waiting at 3rd second and move to next line of command
hence tester can avoid waiting 20 long seconds and save 17 seconds in
this example.*/
Sleep command:
Introducing the line below gives 10 seconds sleeping time to the overall
test execution and halt the entire tests until given duration.
Thread.Sleep(10);

Important note: "Avoid using commands such as Thread.sleep(3000);


in overall regression pack which increases the test execution time rather
than running the tests in short time; Instead thread sleep command, wait
until element present command can be used (refer 'Type2')"-Shweta
Bhat, Code Reviewer

Wait wait = new FluentWait(driver)


.withTimeout(20, SECONDS)
.pollingEvery(2, SECONDS)
.ignoring(NoSuchElementException.class);

WebElement txtUserName = wait.until(new Function() {


public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("<Object ID>"));
}
});
/*FluentWait checks the availability of the object again and again hence
it polls everytime to the browser and check if the object is available or
not.*/

What is Polling?
Polling time is basically next iteration wait time for driver. If object not
found during test execution, WebDriver will come to check the
availabilty of object after 2 sec in the example above
Refer:.pollingEvery(2, SECONDS)

70

Author Copy. Not For Distribution.


Selenium Webdriver

What is Timeout?
Maximum time to wait for an object and it waits for 20 sec in the
example above

What is Ignoring?
Ignores any given exception in the statement. In the above example, if
object not found, browser throws nosuchelementexception and it is
caught by the line below.
Refer:
.ignoring(NoSuchElementException.class)

Some latest interview questions:


1) Is default polling frequency 250 ms is applicable to implicit wait or
explicit wait(of WebDriverWait) or for both type of wait?
Both type of wait (Implicit and Explicit) are applicable to this default
polling frequency of 250milliseconds
2) If implicit wait is 10 sec and element is found in 5 sec, will driver
move to execute next statement after 5 sec or it will wait for
complete 10 sec then move?
Implicit Wait: It will wait till 10 seconds and move to next line of
code
3) If explicit wait is 10 sec and condition is met in 5 sec, will driver
move to execute next statement after 5 sec or it will wait for
complete 10 sec then move?
Explicit Wait: It will execute next statement after 5 seconds when the
object found.

How to get Current web page details?


Before raising the question of how to get current url of the page being
tested, primarily tester should know why such situation occurs to know
the web page address? The answer is based on multiple test environment
testers deal with! When there are different test environments placed such
as SIT,ST,DIT,DT,UAT,UT,UIT,NFT etc, it is hard to leave the tests
running the complete regression pack and realize later that the URL the
tests being conducted are incorrect; In this case the entire test results are
wrong! To avoid such last minute chaos in projects, it is highly suggested
to get url of the page being tested as an output to the logs or excel file
where results are saved. It can be done using the command given below:
driver.getCurrentUrl();

Sample Code of sampletest.java file:


71

Author Copy. Not For Distribution.


Narayanan Palani

@Test
public void sampletest ()
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;

//Get current page title-which is different from URL:


String webpagetitle=
(String)javascript.executeScript("return document.title");
//Result printed in test output:
System.out.println("My Page Title Is : "+webpagetitle);

//Get current page URL-which is different from title:


String CurURL = driver.getCurrentUrl();
//Result printed in test output:
System.out.println("My Current URL Is : "+CurURL);
}

How to generate Alert ?


Alerts are required to get updated in test output to understand and
classify issues during test execution; If there are exceptions after
displaying alerts, it means that the driver has been launched but there
are issues in the xpath or other variables; If there are errors before or no
display or alerts, it is highly possible that the browser driver related
issues would have failed the tests; So alerts help testers to investigate
better during test execution. Below is the sample script to display the
Test Execution Status of Regression Tests:

JavascriptExecutor javascript = (JavascriptExecutor) driver;


javascript.executeScript("alert('Regression Tests are started
Successfully');");

Sample code:
@Test
public void test () throws InterruptedException
{
//Generating Alert Using Javascript Executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert(' Regression Tests are started
Successfully');");
Thread.sleep(3000);

72

Author Copy. Not For Distribution.


Selenium Webdriver

driver.switchTo().alert().accept();
}

How to handle dropdowns in web pages?


List of options are available as dropdown box in many websites. But
automating such dropdown boxes has high probability of failure on
xpath recognition during run time due to incorrect object scripts. So this
section explains on capturing right objects for the dropdown values.

Select by visible Text:


Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Lambogini");

Select by Index:
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='car']")));
listbox.selectByIndex(0);

Deselect by visible Text:


Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='Country']")));
listbox.deselectByVisibleText(India");

Deselect by Value:
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='City']")));
listbox.deselectByValue("Bengaluru");

Deselect by Index:
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='State']")));
listbox.deselectByIndex(2);

Deselect All:
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='Country']")));
listbox.deselectAll();

73

Author Copy. Not For Distribution.


Narayanan Palani

Sample Code to Select dropdown using Index:


package junitreporttestpackage;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class Dropdowntesting {


WebDriver driver = new FirefoxDriver();

@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("page url")
}

@Test
public void test () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Cars")));
drpdwn.selectByVisibleText("Lambogini");
}

@After
public void aftertest() {
driver.quit();
}
}

74

Author Copy. Not For Distribution.


Selenium Webdriver

How to understand a dropdown is multi select or single select?


At times, users are required to select more than one values from
dropdown; It has to be validated using a boolen value and get a return
value of 1 if the dropdown accept multiple selection. It can be done by
using below code:
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='Car']")));
boolean value = listbox.isMultiple();

When the result is 1 then tester can construct an If loop to select


multiple values within the drop down; Else if the result is 0, tester can
route it in the If loop to click on one value of dropdown.
For example:
@Test
public void multidropdowntest () throws InterruptedException
{
Select lst_Citizenship = new
Select(driver.findElement(By.xpath("//select[@name='Citizenship']")));
//To verify that specific select box supports multiple select or not.
if(lst_Citizenship.isMultiple())
{
System.out.print("Dropdown accept multiple selections");
listbox.selectByVisibleText("Canada");
listbox.selectByValue("United Kingdom");
listbox.selectByIndex(2);
Thread.sleep(2000);
//To deselect all selected options and validate them as part of the test:
listbox.deselectAll();
Thread.sleep(2000);
}
else
{
System.out.print("Dropdown does not accept multiple selections");
listbox.selectByValue("United Kingdom");
}
}

How to move forward or backward on the web page?


In manual tests, it is easy to click on Forward or Backward through Back
button and various other options based on the browser facilities.
75

Author Copy. Not For Distribution.


Narayanan Palani

Similarly it is possible to give instructions using code to move forward or


backward with below scripts:
@Test
public void webtest () throws InterruptedException
{
driver.navigate().to("http://google.co.uk");
driver.navigate().to("http://raghava.uk");
driver.navigate().back(); //This line result in going back to google page
driver.navigate().forward(); //This line result in going forward to raghava
page
}

What is the best way to identify if the object or element present in


the web page or not?
Checking the availability of the object within web page is one of the
primary test during test automation execution; It is possible to return the
value 1 if the size is available for the object; Else the test result returns 0
in the below code:
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='emailID1']")).size()!= 0

Sample code:
@Test
public void webelementtest () throws InterruptedException
{
for (int attempt=1; attempt<4; i++)
{
//To verify element is present on the respective page or not:
String XPath = "//input[@id='emailID"+i+"']";
Boolean iselementpresent =
driver.findElements(By.xpath(XPath)).size()!= 0;
if (iselementpresent == true)
{
System.out.print("\nTargeted Email ID Box"+i+" Is Present On The
Page");
}
else
{
System.out.print("\nTargeted Email ID Box"+i+" Is Not Present On The
Page");

76

Author Copy. Not For Distribution.


Selenium Webdriver

}
}
}

How to handle multiple web pages within the particular automation


test?
During the test execution, it is common that multiple pages get opened
and test getting failed at times by not identifying right objects at right
page; This is one of the ongoing challenge within automation tests and it
can be managed by storing the page elements in arrays and perform
actions in each page with window handle mechanism below:
@Test
public void MultiWebPageTest () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page
Here')]")).click();

// Get and store both window handles in array in such a way that all new
pages are getting loaded in Array:
Set<String> AllWindowHandles = driver.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code =
"+AllWindowHandles.toArray()[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code =
"+AllWindowHandles.toArray()[1]);

//Switch to window2(child window) and performing inputs on the page


for the form:
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='firstname']")).sendKeys("
Raghavendra");
Thread.sleep(5000);
//Switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//option[@id='eMailID']")).click();
Thread.sleep(5000);
//Once Again switch to window2(child window) and performing actions
on it.

77

Author Copy. Not For Distribution.


Narayanan Palani

driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='firstname']")).clear();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Ra
ghava");
Thread.sleep(5000);
driver.close();
//Once Again switch to window1(parent window) and performing actions
on top of the Home Page:
driver.switchTo().window(window1);
driver.findElement(By.xpath("//input[@value='Female']")).click();
Thread.sleep(5000);
}

Reference:
 Aravind. (2016, September 07). Software testing tutorials and
automation [Web log post]. Retrieved from http://www.software-
testing-tutorials-automation.com/p/selenium-WebDriver.html
 Syam. (2015, January 29). XLS Reading for DDF [Web log post].
Retrieved from http://pssqtp.blogspot.co.uk/2015/01/xls-reading-
for-ddf.html
 zhaozhiwen (2016, June 16). 手把手教你搭建数据驱动测试框架
[Web log post]. Retrieved from
http://www.jianshu.com/p/206654aeae29

Selenium 3.o Test Scripting


After using Selenium WebDriver versions 2.o for some years (Especially
Firefox 33 version supported by Selenium Standalone 2.45) and
Selenium 3.o has been released and available from 2016.It is highly
recommended to go through this section and see the configuration
changes involved in running the tests.
Download Selenium 3.o from seleniumHQ websitexv on the link
highlighted below:

Figure 53 Download Selenium 3 Beta version (or any latest version)


using Java Programming

78

Author Copy. Not For Distribution.


Selenium Webdriver

In Selenium WebDriver 2.o, there are driver files such as


chromedriver.exe and IEdriverServer.exe required to run in Chrome and
IE browsers; But there is no need of an exe file to run in Firefox browser;
But testers are to add Gecko browser to the scripts in order to run the
Firefox based tests using Selenium 3.o!

Get the Firefox Driver Downloaded from GitHubxvii:

Figure 54 Download Gecko Driver to run Firefox Browser based


Tests using Selenium 3

Test using Gecko Driver in Selenium 3.0 Beta


It is recommended to make changes to the driver initiation scripts as and
when different versions of Firefox are being installed in the test bed
(machine where the tests are getting executed); If Firefox 33 or 45
versions are used, it may not be required to use Desired Capabilities
(additional capabilities to get the browser up and running without
failures); If any Firefox 47 and above versions are used,it is
recommended to use FirefoxProfiling, DesiredCapabilities and/or
marionetteDriver setup when required. Please watch the commented
sections in the script below and them use them as and when firefox
browser launching issues are faced.
Gecko driver is used in this example and screenshots help in respective
setup to run this script:
package com.sfs.SuiteOne;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LaunchBrowser_Firefox {
static WebDriver driver;
public static void main(String[] args){
System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PRO
PERTY,"E://AutomationProject//Training//SFS//BrowserDrivers//gecko
driver.exe");
79

Author Copy. Not For Distribution.


Narayanan Palani

WebDriver driver = new FirefoxDriver();


Wait<WebDriver> wait=new WebDriverWait(driver,30);
driver.get("http://www.yahoo.com");
}
}

Screenshot:

Figure 55 Eclipse IDE Package Explorer View of Scripts

1. Download Selenium 3 jar files from seleniumhq.org and add to build


path
2. Download Geckodriver and add them to BrowserDrivers folder
3. Add a java file to write scripts (refer the scripts above)
4. Scripts are to be updated with right path of the Geckodriver in
property with target machine's latest path
Note:
If there are compatibility issues to firefox and the firefox installed in
target machine, please see the listed options within comments sections to
fix those issues:
package com.sfs.SuiteOne;
import java.util.concurrent.TimeUnit;
import java.io.File;
import org.openqa.selenium.WebDriver;

80

Author Copy. Not For Distribution.


Selenium Webdriver

import org.openqa.selenium.firefox.*;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;
public class LaunchBrowser_Firefox {
static WebDriver driver;
public static void main(String[] args){
//Firefox47.o above and Selenium 3.o -option1:
/*
System.setProperty("WebDriver.gecko.driver","E://AutomationProject//
Training//SFS//BrowserDrivers//geckodriver.exe");
FirefoxProfile p= new FirefoxProfile();
p.setPreference("plugin.disable_full_page_plugin_for_types",
"application/pdf,application/vnd.adobe.xfdf,application/vnd.fdf,applicati
on/vnd.adobe.xdp+xml");
*/
//Firefox47.o above and Selenium 3.o -option2:
/*DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);*/
//Firefox47.o above and Selenium 3.o -option3:
/*String currentDir = System.getProperty("user.dir");
String marionetteDriverLocation = currentDir +
"//BrowserDrivers//geckodriver.exe";
System.setProperty("WebDriver.gecko.driver",
marionetteDriverLocation);
@SuppressWarnings("deprecation")
WebDriver driver = new MarionetteDriver();*/
//Firefox 45.o and Selenium 2.45-option2:
/*
DesiredCapabilities dc=DesiredCapabilities.firefox();
driver = new FirefoxDriver(dc);
*/
//Firefox 45.o and Selenium 2.45-option3:
/*
FirefoxBinary binary = new FirefoxBinary(new File("C:\\Program
Files\\Mozilla Firefox\\firefox.exe"));
FirefoxProfile profile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(binary, profile);
//https://github.com/seleniumhq/selenium-google-code-issue-
archive/issues/7954
81

Author Copy. Not For Distribution.


Narayanan Palani

*/
//Firefox 45.o and Selenium 2.45 -Option1:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.yahoo.com");
}
}

Test using Chrome Driver in Selenium


Get the latest ChromeDriverxviii and place is in the BrowserDrivers folder
within Java Project where Automation Framework has been setup:

Figure 56 Launch Browser Test

When launching the tests, click OK for the security Alerts which may
pop up during first time test execution:

Figure 57 Security Alerts

82

Author Copy. Not For Distribution.


Selenium Webdriver

How to disable Developer Mode Extensions in Chrome Browser


Driver using Selenium 3.o?
When recent chrome browsers are used within fra mnmework, this popup
fails some of the tests and it affects the regression tests scripted in the
past (since the popup is a new behavior in chrome browser driver).
Following is the snapshot of how this popup shown when the test is
getting executed from chrome driver and browser has been launched by
the framework:

Figure 58 Chrome Browser Launched with Extension Details

In order to eliminate the popup mentioned,use Chrome Options and


disable using commands as added arguments:

Figure 59 Script to eliminate the extension popup

package com.sfs.SuiteOne;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class LaunchBrowser {
static WebDriver driver;
public static void main(String[] args){
System.setProperty("WebDriver.chrome.driver","E://AutomationProject/
/Training//SFS//BrowserDrivers//chromedriver.exe");
ChromeOptions options=new ChromeOptions();

83

Author Copy. Not For Distribution.


Narayanan Palani

options.addArguments("--disabled-extensions");
driver = new ChromeDriver(options);
driver.get("www.yahoo.com");
}
}

Behavior Driven Development and Selenium WebDriver


Cucumber is one among the famous tools in Behavior Driven
Development (BDD) in recent years but most of the new comers to
testing industry have questions on what difference it actually makes.
Software tests are made in pure english using BDD (as a major
advantage) and then plugged to programming functions within step
definition files as next step(.java file within cucumber.features folder in
the below example:

Figure 60 Sample BDD Project

Script Reference:
 https://github.com/narayananpalani/testautomation/tree/master/017L
androverTestProject_Shivani

84

Author Copy. Not For Distribution.


Selenium Webdriver

Please download the complete project from above link using Download
Zip option and read the details further for better understanding and
clarity of the project design.

Prerequisites to setup BDD based Selenium Project:


Install Cucumber,Jar files to project path (learn from Part 1 book on step
by step instructions)

Steps to implement:
Create a project within Eclipse and create two packages in the name
cucumber and cucumber.features (follow the pictures for examples);
Once created packages,create TestRun.java file and just copy the below
code:
package cucumber;
//import cucumber.api.CucumberOptions;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format = {"pretty","html:target/cucumber-html-
report", "json:target/cucumber-report.json"},
features = {"src/cucumber/testlandrover.feature"})
public class TestRun {
}

This TestRun is the primary file to run the tests using Cucumber;The
next step is to create a .feature file within cucumber.features package like
the below:

85

Author Copy. Not For Distribution.


Narayanan Palani

Figure 61 Sample Feature File with Gherkin Scripts

Feature: Testing for Landrover Project


Scenario: Validate Above and Beyond of Landrover Web Page
Given Landrover page is open in InternetExplorer
When I click on AboveandBeyond Tab and verify FINDOUTMORE
button
Then I see the AboveandBeyond Section of Landrover Page
Note: If you see the green cucumber logo on the feature file(within
package explorer) then you have installed cucumber successfully. Else it
has to be installed in Help->Install New Software [Please refer Part1
Book on this]

What is Feature file?


Test Scenarios/Testable Requirements are written in the format of
Given,When and Then and it needs a little bit of logical analysis of any
test scenarios and then nothing else!
Example:
If you want to travel from Paris to Amsterdam ,what would be the
Scenario within feature file?
Feature: Travelling from Paris to Amsterdam
Scenario: Travel in Thalys Train from Paris Gare du Nord to
Amsterdam Central Station
Given customer hold valid ticket to travel in thalys train
When customer touch in the ticket in Paris Gare du Nord station
And customer board on Coach 39 of thalys train at 10AM on 06Aug2018
Then customer reached Amsterdam Central Station and touch out the
ticket

Explanation: Given is a prerequisite step or the condition for the tests;


Note there are When and And in second and third row which represents
like When only. It means:
When customer touch in the ticket in Paris Gare du Nord station

86

Author Copy. Not For Distribution.


Selenium Webdriver

When customer board on Coach 39 of thalys train at 10AM on


06Aug2018
Instead repeating many 'When' within the lines of code, it is reduced to
And (when the earlier row is 'When')
Similarly follow another example:
Given customer hold valid ticket to travel in thalys train
When customer touch in the ticket in Paris Gare du Nord station
And customer board on Coach 39 of thalys train at 10AM on 06Aug2018
Then customer reached Amsterdam Central Station and touch out the
ticket
And Amsterdam CS ticket gate open successfully allowing customer to
go out
In the example above, both the lines Then and And(below Then) refers to
Then type of code only:
Then customer reached Amsterdam Central Station and touch out the
ticket
Then Amsterdam CS ticket gate open successfully allowing customer to
go out
In the project example,create a .java file within cucumber.features
package and follow the scripts beow:

Figure 62 Step Definitions

Package name of the script:


package cucumber.features;
This file helps in interacting to other files within java framework:
import java.io.File;

87

Author Copy. Not For Distribution.


Narayanan Palani

This IOException helps in catching the issues during the compilation and
test execution:
import java.io.IOException;
import org.apache.commons.io.FileUtils;
Selenium files to handle automation engine control over the target
application:
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
Various drivers for the automation project are listed here. Based on the
needs, user can pick respective driver for the test:
//import org.openqa.selenium.android.AndroidDriver;
import org.openqa.selenium.chrome.ChromeDriver;
//import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
//import org.openqa.selenium.iphone.IPhoneDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
//import org.openqa.selenium.safari.SafariDriver;
Java Utility file:
import java.util.concurrent.TimeUnit;
//import com.sun.jna.platform.FileUtils;
Cucumber files to help the given, when, and, then model of scripts are
listed here. If Then is missing in the import(as an example),it throw error
during compilation:
//import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
//import cucumber.api.java.en.And;
//import cucumber.runtime.PendingException;
public class landrover {
//private static final String FILE = null;
public WebDriver browser;
See the below script on @Before. This is the primary reason why
following test results are logged during test execution:
Console based Test Results:
88

Author Copy. Not For Distribution.


Selenium Webdriver

Feature: Testing for Landrover Project


*******************
launching Chrome browser
Scenario: Validate Above and Beyond of Landrover Web Page #
E:\AutomationProject\Training\LandroverTestProject_Shivani\src\cucum
ber\features\testlandrover.feature:3
Starting ChromeDriver 2.20.353145
(343b531d31eeb933ec778dbcf7081628a1396067) on port 9055
Only local connections are allowed.

Script which help in getting this test log is:


@Before
public void setUp() {
System.out.println("*******************");
System.out.println("launching Chrome browser");
//System.setProperty("WebDriver.ie.driver",
"E://AutomationProject//Training//LandroverTestProject//BrowserDrive
rs//IEDriverServer.exe");
System.setProperty("WebDriver.chrome.driver",
"E:/AutomationProject/Training/LandroverTestProject/BrowserDrivers/
ChromeDriver.exe");
}

Script for Given line of .feature file is scripted here:


Note: Follow the first two lines of the code in the below; @Given is
carefully linked to public void script in the next line; When getting
executed, feature file search for the Given statement presented in the
feature file and finds this line and then directly execute the scripts below:
@Given("^Landrover page is open in InternetExplorer$")
public void Landrover_page_is_open_in_InternetExplorer()
{
//DesiredCapabilities ieCapabilities =
DesiredCapabilities.internetExplorer();
//ieCapabilities.getCapability(InternetExplorerDriver.INTRODUCE_FL
AKINESS_BY_IGNORING_SECURITY_DOMAINS);
//this.browser=new InternetExplorerDriver(ieCapabilities);
//throw new PendingException();
//browser=new InternetExplorerDriver();
browser=new ChromeDriver();
This line help in getting the website to be launched:

89

Author Copy. Not For Distribution.


Narayanan Palani

browser.get("<website URL>");
}

'When' script in the step definition file which connects from feature file
and execute the action below:
@When("^I click on AboveandBeyond Tab and verify FINDOUTMORE
button$")
public void
I_click_on_AboveandBeyond_Tab_and_verify_FINDOUTMORE_button
()
{
The id mentioned in the line below has to be identified using xpath within
the page and then update in this code. (refer object capturing techniques
chapter: 'Object Capturing Techniques for Automation Testing' related
to this method)
browser.findElement(By.id("MainNavigation:ABOVE AND
BEYOND:/above-and-beyond/index.html")).click();
//browser.findElement(By.id("HeroCarousel:FIND OUT
MORE:https://live.landrover.co.uk/")).click();
browser.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//String value = browser.findElement(By.id("295-82654")).getText();
//browser.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//browser.findElement(By.cssSelector("span.image.backgroundImage")).
click();
browser.findElement(By.id("MainNavigation:ABOVE AND
BEYOND:/above-and-beyond/index.html")).click();
browser.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
browser.findElement(By.id("HeroCarousel:FIND OUT MORE:/above-
and-beyond/reborn.html")).click();
}
'Then' script which updates the test results with TEST PASS:
@Then("^I see the AboveandBeyond Section of Landrover Page$")
public void I_see_the_AboveandBeyond_Section_of_Landrover_Page()
{
System.out.println("TEST PASS");
}
}

How to execute this script?


Click on the feature file, right click->Run As->Cucumber Feature

90

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 63 Running the BDD Tests in Cucumber

Once executed, it runs the script below:

Figure 64 Test Execution Started

Once completely executed, following texts appear in test results:

Figure 65 Test Execution Results in Output Console

Console based Complete Test Results:


Feature: Testing for Landrover Project
*******************
launching Chrome browser
Scenario: Validate Above and Beyond of Landrover Web Page #
E:\AutomationProject\Training\LandroverTestProject\src\cucumber\featu
res\testlandrover.feature:3
Starting ChromeDriver 2.20.353145
(343b531d31eeb933ec778dbcf7081628a1396067) on port 9055
Only local connections are allowed.
Given Landrover page is open in InternetExplorer #
landrover.Landrover_page_is_open_in_InternetExplorer()

91

Author Copy. Not For Distribution.


Narayanan Palani

When I click on AboveandBeyond Tab and verify FINDOUTMORE


button #
landrover.I_click_on_AboveandBeyond_Tab_and_verify_FINDOUTM
ORE_button()
TEST PASS
Then I see the AboveandBeyond Section of Landrover Page#
landrover.I_see_the_AboveandBeyond_Section_of_Landrover_Page()

Script to search Google using Selenium WebDriver and JUnit


When Google search is performed, it is easy to capture three objects and
complete automating the page for a particular google search; If we do
not know what kind of google search performed every time and if that
search word has to be properly identified whether it is available in the
results or not; Hence every search query has to be performed as a
function and match the query to search results in another function. This
part of the Part2 book explains on constructing such sample script.
Script location in GIT:
\SAF\src\com\stta\SeleniumBasics\GoogleSearch_WebTest.java
Programming Language: Java Programming

package com.stta.SeleniumBasics;
import java.util.concurrent.TimeUnit;

JUnit tests are using Before,After and Test methods of Junit and
following imports are required in such cases:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

This section is getting executed before the actual test using JUnit and
@Before is the tag of JUnit:
@Before
public void setUp() throws Exception {
//DesiredCapabilities dc=DesiredCapabilities.firefox();
//driver = new FirefoxDriver(dc);

Property of browser is set to take the browser file from respective local
machine's location. Tester has to get this path updated before running the
test:

92

Author Copy. Not For Distribution.


Selenium Webdriver

System.setProperty("WebDriver.chrome.driver",
System.getProperty("user.dir")+"//BrowserDrivers//chromedriver.exe");
driver = new ChromeDriver();

Whenever the browser is launched,it takes nearly 20 seconds to open the


web page due to delay from wifi internet connectivity issues hence after
launching browser for respective page,it is waiting for 20 seconds to load
the full browser:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}

This particular function exactly search and match the results to validate
the search results:
@Test
public void basicGoogleFindTest() {
GoogleSearch googleweb = new GoogleSearch(driver);
googleweb.searchFor("Software Automation Testing Secrets Revealed");
boolean txt_result = googleweb.searchResultPresent("Software
Automation Testing Secrets Revealed");
assert (txt_result == true);
}

After finishing those main tests, @After can be called and driver.close();
or driver.quiet(); can be used based on needs:
@After
public void tearDown() throws Exception {
driver.quit();
}
}

Following are the objects captured and listed in the test:


By searchBox = By.id("lst-ib");
By searchResponse = By.cssSelector("#rso .g");
By searchBoxSubmit = By.id("tsf");

This assert section helps in verifying the search result page fro
google.com:
assert (verifyPage() == true);

93

Author Copy. Not For Distribution.


Narayanan Palani

Before searching in every test, search box has been cleared out to get
right results:
driver.findElement(searchBox).clear();

Search term has been sent to the search box and sendKeys is used to send
the particular text through object searchTerm:
driver.findElement(searchBox).sendKeys(searchTerm);

Once search item entered on search box, search button can be pressed
using click(); command:
driver.findElement(searchBoxSubmit).click();
}

Test Results in Eclipse IDE:

Figure 66 Test Results

Figure 67 Test Results of BDD Feature File

94

Author Copy. Not For Distribution.


Selenium Webdriver

Reference:
 Matt,B. (2016, June 30)cucumber-js-selenium-WebDriver-example
[Web log post]. Retrieved from https://github.com/Matt-
B/cucumber-js-selenium-WebDriver-example
 Dave H@tourdedave ,elemental-selenium-tips [Web log post].
Retrieved from https://github.com/tourdedave/elemental-selenium-
tips

How to write the same tests in Ruby and run in TestWise?


Top Insurance companies of UK are chosen to use Ruby based Watir
tests and other Ruby based frameworks and then the industry focus of
automation frameworks are pretty much targeted across ruby scripting
techniques hence it is important to know basic scripting techniques in
ruby language and it will help in Ruby on Rails projects and other tools
compatible to Ruby scripting as well.
Programming Languae:Ruby
Tool Used: TestWise

Similar to Imports used in Java programming, require is the keyword


used in Ruby programming and following files are required for the tests:
require 'selenium-WebDriver'
require 'rspec-expectations'

Firefox browser is used in this test:


def setup
@driver = Selenium::WebDriver.for :firefox

URL of the website has been sent through the code below:
ENV['txt_url'] = 'http://www.google.co.in'

To close the browser:


def teardown
@driver.quit
end

In order to execute the tests, three functions, such as setup,yield and


teardown are called within run function and objects are captured in the
format given below.Objects captured on the Google Page with id and css
selectors.This might change based on the google page's version.
SEARCH_BOX = { id: 'lst-ib' }

95

Author Copy. Not For Distribution.


Narayanan Palani

SEARCH_BOX_SUBMIT = { id: 'tsf' }


SEARCH_RESPONSE = { css: '#rso .g' }

Browser initialised in this section to visit the particular url given in the
code earlier:
def initialize(driver)
@driver = driver
visit
verify_page
end

URL of the website is referred in this script:


def visit
driver.get ENV['txt_url']
end

When 'google.search_for 'elemental selenium WebDriver tips'' is called


in Run section, it is executed through the line below:
def search_for(search_term)
driver.find_element(SEARCH_BOX).clear
driver.find_element(SEARCH_BOX).send_keys search_term
driver.find_element(SEARCH_BOX_SUBMIT).click
end

Search results are matched and compared in this section:


def search_result_present?(search_result)
wait_for { displayed?(SEARCH_RESPONSE) }
driver.find_element(SEARCH_RESPONSE).text.include? search_result
end

Google page is verified whether it contains Google as title or not?:


def verify_page
driver.title.include?('Google').should == true
end

Page wait for 5 seconds using these code snippets:


def wait_for(seconds=5)
Selenium::WebDriver::Wait.new(:timeout => seconds).until { yield }
end

96

Author Copy. Not For Distribution.


Selenium Webdriver

Search results are validated using this script:


def displayed?(locator)
driver.find_element(locator).displayed?
true
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
end

This is the main section of this ruby code to run the search query and
compare results:
run {
google = GoogleSearch.new(@driver)
google.search_for 'Software Automation Testing Secrets Revealed'
result = google.search_result_present? 'Software Automation Testing
Secrets Revealed'
result.should == true
}

Reference:
 Dave H@tourdedave ,elemental-selenium-tips [Web log post].
Retrieved from
https://github.com/tourdedave/elemental-selenium-tips

Proof Of Concept (PoC)-Selenium WebDriver Based Test


Automation Framework
Every project need a basic PoC to understand the tool suitability to the
overall project along with its strength and weaknesses; Implementing an
incorrect tool or best tool at incorrect time may affect project expenses
and cause failures to the test automation projects. Hence this section
explains about what sections required for preparing a sample proof of
concept on Selenium WebDriver based automation framework.

1. Definition
Test Automation Implementation required strong project expertise and
sampling results how certain automation tools provide benefits to the
project; In order to implement any new tool to the testing projects and
cycles, it is highly recommended to perform Proof of Concept on such
tools and evaluate the fitment. Selenium WebDriver2.o has been taken

97

Author Copy. Not For Distribution.


Narayanan Palani

into consideration in this PoC to understand how best it fits to the project
and provide Return on Investment.

2. Introduction
Selenium WebDriver based Automation Framework consists of set of
tools and processes to get implemented in web based testing cycles
carried over agile projects; This can be done by downloading the
Selenium WebDriver based java jar files from SeleniumHQxix.
Selenium 2.o version has been identified to construct the automation
framework and then it eventually support Firefox 33.o browser along
with Chrome and IE browsers for the PoC.

3. Automation PoC approach


As a prerequisite to the automation project, subset of manual test cases
are identified and selected for converting them to automation tests.

4. PoC Considerations
Java based Selenium Automation Framework has been considered for the
PoC and other frameworks such as C#,Python, Ruby and Java Script
based frameworks are not included in the PoC; Similarly Selenium 2.o is
identified to be used for the tests rather than selecting other tools such as
TestComplete, UFT (formerly QTP),Rational Functional Test, Silk Test
etc; Eclipse IDE (Luna version) has been selected rather than using latest
IDEs such as IntelliJ etc.
Following Page has been considered to get automated to validate the
Page Input Submission:
https://docs.google.com/forms/d/1vlQmYGyNXYMPhuLRSAJ25LtWN
eZyzYxXYMdz7WUo98w/viewform?c=0&w=1

Test Scenario: Successful submission of HR Verification Form


Test Case: Submit candidate inputs for HR verification successfully

98

Author Copy. Not For Distribution.


Selenium Webdriver

Screenshot of the Page to be Automated:

Figure 68 Sample Page Created using Drive.Google.Com


to test the objects

Part of Page Source (Xpath highlighted for an object):


<div class="ss-required-asterisk" aria-
hidden="true">*Required</div></div></div>

99

Author Copy. Not For Distribution.


Narayanan Palani

<div class="ss-form"><form
action="https://docs.google.com/forms/d/e/1FAIpQLScLxTQWgPTnbx
Ti3uLQNPE2z4r8S_ZRcGTbfSU--WfGNDzQ0Q/formResponse"
method="POST" id="ss-form" target="_self" onsubmit=""><ol
role="list" class="ss-question-list" style="padding-left: 0;">
<div class="ss-form-question errorbox-good" role="listitem">
<div dir="auto" class="ss-item ss-item-required ss-text"><div class="ss-
form-entry">
<label class="ss-q-item-label" for="entry_1000000"><div class="ss-q-
title">Full Name
<label for="itemView.getDomIdToLabel()" aria-label="(Required
field)"></label>
<span class="ss-required-asterisk" aria-hidden="true">*</span></div>
<div class="ss-q-help ss-secondary-text" dir="auto"></div></label>

5. PoC Outcomes
Following line of codes are written to automate the target web page:
package com.stta.SuiteOne;
import java.io.IOException;
import org.openqa.selenium.By;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import com.stta.utility.Read_XLS;
import com.stta.utility.SuiteUtility;
//SuiteOneCaseOne Class Inherits From SuiteOneBase Class.
//So, SuiteOneCaseOne Class Is Child Class Of SuiteOneBase Class And
SuiteBase Class.
public class SuiteOneCaseOne extends SuiteOneBase{
Read_XLS FilePath = null;
String SheetName = null;
String TestCaseName = null;
String ToRunColumnNameTestCase = null;
String ToRunColumnNameTestData = null;
String TestDataToRun[]=null;
static boolean TestCasePass=true;

100

Author Copy. Not For Distribution.


Selenium Webdriver

static int DataSet=-1;


static boolean Testskip=false;
static boolean Testfail=false;
SoftAssert s_assert =null;

@BeforeTest
public void checkCaseToRun() throws IOException{
//Called init() function from SuiteBase class to Initialize .xls Files
init();
//To set SuiteOne.xls file's path In FilePath Variable.
FilePath = TestCaseListExcelOne;
TestCaseName = this.getClass().getSimpleName();
//SheetName to check CaseToRun flag against test case.
SheetName = "TestCasesList";
//Name of column In TestCasesList Excel sheet.
ToRunColumnNameTestCase = "CaseToRun";
//Name of column In Test Case Data sheets.
ToRunColumnNameTestData = "DataToRun";
//Bellow given syntax will Insert log In applog.log file.
Add_Log.info(TestCaseName+" : Execution started.");
//To check test case's CaseToRun = Y or N In related excel sheet.
//If CaseToRun = N or blank, Test case will skip execution. Else It will
be executed.
if(!SuiteUtility.checkToRunUtility(FilePath,
SheetName,ToRunColumnNameTestCase,TestCaseName)){
Add_Log.info(TestCaseName+" : CaseToRun = N for So Skipping
Execution.");
//To report result as skip for test cases In TestCasesList sheet.
SuiteUtility.WriteResultUtility(FilePath, SheetName, "Pass/Fail/Skip",
TestCaseName, "SKIP");
//To throw skip exception for this test case.
throw new SkipException(TestCaseName+"'s CaseToRun Flag Is 'N' Or
Blank. So Skipping Execution Of "+TestCaseName);
}
//To retrieve DataToRun flags of all data set lines from related test data
sheet.
TestDataToRun = SuiteUtility.checkToRunUtilityOfData(FilePath,
TestCaseName, ToRunColumnNameTestData);
}

101

Author Copy. Not For Distribution.


Narayanan Palani

//Accepts 4 column's String data In every Iteration.


@Test(dataProvider="SuiteOneCaseOneData")
public void SuiteOneCaseOneTest(String DataCol1,String
DataCol2,String DataCol3,String DataCol4, String DataCol5,String
DataCol6, String DataCol7,String DataCol8,String ExpectedResult)
{
DataSet++;
//Created object of TestNG SoftAssert class.
s_assert = new SoftAssert();
//If found DataToRun = "N" for data set then execution will be skipped
for that data set.
if(!TestDataToRun[DataSet].equalsIgnoreCase("Y")){
Add_Log.info(TestCaseName+" : DataToRun = N for data set line
"+(DataSet+1)+" So skipping Its execution.");
//If DataToRun = "N", Set Testskip=true.
Testskip=true;
throw new SkipException("DataToRun for row number "+DataSet+" Is
No Or Blank. So Skipping Its Execution.");
}
//If found DataToRun = "Y" for data set then bellow given lines will be
executed.
//To Convert data from String to Integer
//int ValueOne = Integer.parseInt(DataCol1);
// int ValueTwo = Integer.parseInt(DataCol2);
//int ValueThree = Integer.parseInt(DataCol3);
//int ExpectedResultInt = Integer.parseInt(ExpectedResult);
//To Initialize Firefox browser.
loadWebBrowser();
driver.get(Param.getProperty("siteURL"));
driver.findElement(By.xpath("id('entry_1000000')")).sendKeys(DataCol
1);
//getElementByName("Laevistrombus canarium").click();
driver.findElement(By.xpath("id('entry_1000013')")).sendKeys(DataCol
2);
driver.findElement(By.xpath("id('entry_1000014')")).sendKeys(DataCol
3);
driver.findElement(By.xpath("id('group_1000001_1')")).click();
driver.findElement(By.xpath("id('group_1000001_2')")).click();
driver.findElement(By.xpath("id('group_1000001_3')")).click();

102

Author Copy. Not For Distribution.


Selenium Webdriver

driver.findElement(By.xpath("id('entry_1000002')")).sendKeys(DataCol
4);
driver.findElement(By.xpath("id('entry_1000003')")).sendKeys(DataCol
5);
driver.findElement(By.xpath("id('entry_1000004')")).sendKeys(DataCol
6);
driver.findElement(By.xpath("id('entry_1000005')")).sendKeys(DataCol
7);
driver.findElement(By.xpath("id('group_1000006_1')")).click();
driver.findElement(By.xpath("id('group_1000006_2')")).click();
driver.findElement(By.xpath("id('group_1000006_3')")).click();
driver.findElement(By.xpath("id('group_1000007_1')")).click();
driver.findElement(By.xpath("id('group_1000007_2')")).click();
driver.findElement(By.xpath("id('group_1000008_1')")).click();
driver.findElement(By.xpath("id('group_1000008_2')")).click();
driver.findElement(By.xpath("id('entry_1000009')")).sendKeys(DataCol
8);
driver.findElement(By.xpath("id('group_1000011_1')")).click();
driver.findElement(By.xpath("id('group_1000011_2')")).click();
driver.findElement(By.xpath("id('group_1000011_3')")).click();
driver.findElement(By.xpath("id('group_1000011_4')")).click();
driver.findElement(By.xpath("id('group_1000011_5')")).click();
driver.findElement(By.xpath("id('group_1000011_6')")).click();
driver.findElement(By.xpath("id('group_1000011_7')")).click();
driver.findElement(By.xpath("id('group_1000011_8')")).click();
driver.findElement(By.xpath("id('group_1000011_9')")).click();
driver.findElement(By.xpath("id('group_1000011_10')")).click();
driver.findElement(By.xpath("id('group_1000011_11')")).click();
driver.findElement(By.xpath("id('group_1000012_1')")).click();
driver.findElement(By.xpath("id('group_1000012_2')")).click();
driver.findElement(By.xpath("id('group_1000012_3')")).click();
driver.findElement(By.xpath("id('group_1000012_4')")).click();
driver.findElement(By.xpath("id('group_1000012_5')")).click();
driver.findElement(By.xpath("id('ss-submit')")).click();
String Result = getElementByName("txt_Result").getAttribute("value");
//To Convert data from String to Integer
int ActualResultInt = Integer.parseInt(Result);
//Compare actual and expected values.
if(Testfail){

103

Author Copy. Not For Distribution.


Narayanan Palani

//At last, test data assertion failure will be reported In testNG reports and
It will mark your test data, test case and test suite as fail.
s_assert.assertAll();
}
}

//@AfterMethod method will be executed after execution of @Test


method every time.
@AfterMethod
public void reporterDataResults(){
if(Testskip){
Add_Log.info(TestCaseName+" : Reporting test data set line
"+(DataSet+1)+" as SKIP In excel.");
//If found Testskip = true, Result will be reported as SKIP against data
set line In excel sheet.
SuiteUtility.WriteResultUtility(FilePath, TestCaseName,
"Pass/Fail/Skip", DataSet+1, "SKIP");
}
else if(Testfail){
Add_Log.info(TestCaseName+" : Reporting test data set line
"+(DataSet+1)+" as FAIL In excel.");
//To make object reference null after reporting In report.
s_assert = null;
//Set TestCasePass = false to report test case as fail In excel sheet.
TestCasePass=false;
//If found Testfail = true, Result will be reported as FAIL against data set
line In excel sheet.
SuiteUtility.WriteResultUtility(FilePath, TestCaseName,
"Pass/Fail/Skip", DataSet+1, "FAIL");
}else{
Add_Log.info(TestCaseName+" : Reporting test data set line
"+(DataSet+1)+" as PASS In excel.");
//If found Testskip = false and Testfail = false, Result will be reported as
PASS against data set line In excel sheet.
SuiteUtility.WriteResultUtility(FilePath, TestCaseName,
"Pass/Fail/Skip", DataSet+1, "PASS");
}
//At last make both flags as false for next data set.
Testskip=false;
Testfail=false;

104

Author Copy. Not For Distribution.


Selenium Webdriver

}
//This data provider method will return 4 column's data one by one In
every Iteration.
@DataProvider
public Object[][] SuiteOneCaseOneData(){
return SuiteUtility.GetTestDataUtility(FilePath, TestCaseName);
}
//To report result as pass or fail for test cases In TestCasesList sheet.
//@AfterTest
public void closeBrowser(){
//To Close the web browser at the end of test.
closeWebBrowser();
if(TestCasePass){
Add_Log.info(TestCaseName+" : Reporting test case as PASS In
excel.");
SuiteUtility.WriteResultUtility(FilePath, SheetName, "Pass/Fail/Skip",
TestCaseName, "PASS");
}
else{
Add_Log.info(TestCaseName+" : Reporting test case as FAIL In
excel.");
SuiteUtility.WriteResultUtility(FilePath, SheetName, "Pass/Fail/Skip",
TestCaseName, "FAIL");
}
}
}

As per the initial evaluation on the Selenium based Java Automation


Frameworks, the proof of concept is completed successfully and all web
based test cases selected during this process are successfully automated.
Post successful completion of Proof of Concept, script has been uploaded
in GitHub for reference:
https://github.com/narayananpalani/testautomation/tree/master/SAF

6. Assumptions and Dependencies


Assuming that the JAVA has been installed in the Target Machine and
JAVA_HOME and PATH are updated.
When the Java Project (automation framework) is imported in latest
version of Eclipse, the project may get updated with latest eclipse

105

Author Copy. Not For Distribution.


Narayanan Palani

compatibility scripts and it may not get imported in older version of


eclipse.

7. Risks Associated
Re-installation of browsers and additional Addins to the browsers and
change of Operating System to the target machine are critical factors to
relook and amend the automation framework to work in latest test
environments. If Selenium 3.o is implemented to the framework, gecko
driver is to be used for firefox tests which is a high risk at the moment as
beta version of Selenium 3.o is likely to fail for gecko driver or
marionette drivers as on 28Aug2016 (which may change later period of
time based on the upgraded versions of Selenium)
If the browsers are upgraded to later versions for firefox (example
47 and above) which will not be compatible to the automation
framework constructed as part of this PoC. Similarly change in
Operating Systems from Win 2007 to later versions may impact the
current automation framework built for the PoC.

8. Problems in Automation
It is not possible to automate the applications other then web pages in
selected Selenium based Automation Framework.

9. Methodologies for PoC Approach


Data Driven Framework methods are used to design the automation
framework and web elements are captured using Xpath methodologies;

10. Advantages of PoC


Performing PoC provides a better understanding on Automation
Framework Implementation; creating the framework during PoC phase
helps in estimating the Return on Investment calculations with the
following inputs:

Testing Activity Before PoC After PoC


Writing a Test Case 30minutes 40min
Test Execution 20minutes 0.3 minutes
Test Amendments 10minutes 10minutes

11. Entry Criteria


Objects of web elements should be made available from Dev Team; Test
environment should be available to perform PoC.

106

Author Copy. Not For Distribution.


Selenium Webdriver

12. Exit Criteria


Once PoC is designed and presented without Open Defects within
Automation Framework successfully, the PoC phase of scripting can be
closed.

13. Test Architecture


 Cross Browser Compatibility
Tests
Included in TestNG XML
SAF/test-output

LoadWebBrowser();
Called in the test case at
SAF/src/com/stta/SuiteOne

LoadWebBrowser Function
in
SAF/src/com/stta/TestSuiteBase

Browser Selection
In param.properties
SAF/src/com/stta/property

Test Execution

Firefox Driver Chrome Driver IE Driver Server


From Selenium From BrowserDrivers folder From BrowserDrivers folder
<No driver exe required> SAF/BrowserDrivers SAF/BrowserDrivers
Figure 69 Cross Browser Compatibility

107

Author Copy. Not For Distribution.


Narayanan Palani

 Screenshot Capability of Automation Framework


Screenshot Listener
in TestNG XML
SAF/test-output

Screenshot Utility
SAF/src/com/stta/utility

Screenshot Parameter
in param.properties
SAF/test-output

Location of Screenshots
SAF/screenshots

Test Failure Screenshot Test Pass Screenshot


in FAIL Test Execution PASS in
SAF/screenshots/Failure SAF/screenshots/Success

Figure 70 Screenshot Capability

108

Author Copy. Not For Distribution.


Selenium Webdriver

 Object Repository Capability


<test name="SuiteOneCaseOne">
<classes>
<class name="com.stta.SuiteOne.SuiteOneCaseOne" >
</class>
</classes>
</test>

Test
included in TestNG XML
SAF/test-output

Test Case
Updated in SuiteOne Folder
SAF/src/com/stta/SuiteOne

Reusable Components
Updated in SuiteBase
SAF/src/com/stta/TestSuiteBase

Object Properties
Updated in object.properties
SAF/src/com/stta/property
Figure 71 Object Repository

109

Author Copy. Not For Distribution.


Narayanan Palani

 SiteURL Management using Parameters


<test name="SuiteOneCaseOne">
<classes>
<class name="com.stta.SuiteOne.SuiteOneCaseOne" >
</class>
</classes>
</test>

Test
included in TestNG XML
SAF/test-output

driver.get(“SiteURL”);
Test Case
Updated in SuiteOne Folder
SAF/src/com/stta/SuiteOne

Reusable Components
Updated in SuiteBase
SAF/src/com/stta/TestSuiteBase

SiteURL
Updated in param.properties
SAF/src/com/stta/property
Figure 72 Parameter Management

110

Author Copy. Not For Distribution.


Selenium Webdriver

 XSLT Reporting Capability


Tests
Included in TestNG XML
SAF/test-output

TestNG configuration for


XSLT Report
Included in testng-result.xsl
SAF/src/com/stta/xslt

“testng-results.xml” “emailable-report.html”
Updated in XML Test Execution XSLT updated in
SAF/test-output SAF/test-output

Figure 73 XSLT Reporting Capability

111

Author Copy. Not For Distribution.


Narayanan Palani

 Logging Capability
Tests
Included in TestNG XML
SAF/test-output

Log4J configuration for


Logs
Included in log4j.properties
SAF/src/com/stta/xslt

Test Execution

Logs

“applog.log”
updated in
SAF/src/com/stta/Logging

Figure 74 Logging Capability

14. Scripting Guidelines


Naming Standards in Java based Test Classes
Data Type Suggested Prefix Examples
Global g gStrtype
Module-level m mIntID
Static s sintdob
Variable Passed by Reference r rIntID
Variable Passed by Values v vintAge
112

Author Copy. Not For Distribution.


Selenium Webdriver

Local to the Function None strName


Boolean bin binStatus
Integer int intID
Long lng lngRef
Double dbl dblCount
Object obj objNext
String str strName
Single sng sngRow
Array arr arrProducts
User-Defined Type udt udtStock

15.Design for Sustainability


Software Supported Not Supported
Selenium 2.45.o 3.o Beta
Firefox 33.o to 46.o 47+
IE 7,8,9,10 6,11
Chrome 2.o Latest Beta versions

16. Feasibility Study


Type of Feasibility Possible?
Screenshot Capture Yes
Log4J Integration Yes
Parameterisation Yes
Core Component Framework Development Yes
Cross Browser Compatibility (IE,Chrome,Firefox) Yes
XSLT Reporting Yes
Data Inputs from Excel Files Yes
Reusable Functions Library Yes
Test Suite Hierarchy Yes
TestNG Execution Yes
JUnit Execution Yes
Ant Build Yes
Maven Build Yes
Jenkins Job Scheduling Yes
Web Automation Yes

113

Author Copy. Not For Distribution.


Narayanan Palani

Standalone Automation No
Android Automation No

17. Prove the Concept


Since web automation in Firefox 46,IE8 and Chrome 2.o are 100%
possible and proven with Selenium WebDriver 2.45.o version using Java
1.8 (JDK), it is proposed to implement for automation framework
implementation.
18.Examples for Automation PoC
Examples are given in Appendix B

Selenium Web Driver Scripts to build Automation Framework


This section discuss about the primary scripts required to develop the
selenium automation framework and please refer the first part of the
book: 'Software Automation Testing Secrets Revealed' to understand how
to install and setup this automation framework.
Designing automation framework and running the automation tests
using such framework is the desired skillset expected from each
automation tester and this skillset needs knowledge on multiple tools
such as Selenium WebDriver,TestNG,JUnit etc.
Unlike famous test automation tools such as Unified Functional Test
(formerly QTP),Rational Functional Test and SilkTest, there is no GUI
look available for Selenium at the moment and we can easily build and
write scripts using Eclipse or IntelliJ; When selenium jar files are
downloaded from seleniumhq site, it has to be extended visa Project
Build Path of Eclipse and the complete instructions of Installation and
configuration steps are given in Part 1 of this book (chapter11).
Once automation framework is configured, SuiteBase.java is the
first java file to start writing programming scripts to automate web
applications. Also it is not suggested to write entire set of test scripts
within single file due high maintenance issues. When test cases
converted from manual tests, it is ideal to write each individual tests as
SuiteOneCaseOne,SuiteOneCaseTwo and so on. Once scripts are
developed, they can be extended to SuiteOne class and then SuiteOne get
extended to primary script file TestSuiteBase(scripts explained below). If
we follow such test scripts split, it is easy to assign test scripts to
automation testers and get them committed and pushed to repositories in
less time.
Example:
Test Shopping Cart of the Online Sales Website
Scenarios:
114

Author Copy. Not For Distribution.


Selenium Webdriver

Test SuiteBase: Shopping Cart


1. Suite One: Login
1.1. SuiteOneCaseOne: Login with valid user id and password of
customers using Chrome
1.2. SuiteOneCaseTwo: Login with valid admin id and password of
Administrator using IE7
2. SuiteTwo:Add to Shopping Cart
2.1. SuiteTwoCaseOne: Add one product to shopping cart using
Firefox
2.2. SuiteTwoCaseTwo:Add multiple products to shopping cart
using Chrome
2.3. SuiteTwoCaseThree:Add multiple products to shopping cart
and delete multiple products from shopping cart using IE8
2.4. SuiteTwoCaseFour:Add products to shopping cart,logout and
login to validate the products added to shopping cart in earlier
session using Firefox
3. SuiteThree:Shopping Cart Product Unavailability
3.1. SuiteThreeCaseOne:Add products to shopping cart and view
product availability status
3.2. SuiteThreeCaseTwo:Add products to shopping cart and view
product discount
3.3. SuiteThreeCaseThree:Add products to shopping cart and view
discounts and offers
4. SuiteFour:Payment
4.1. SuiteFourCaseOne:Add products to shopping cart and make
payment using debit card
4.2. SuiteFourCaseTwo:Add products to shopping cart and make
payment using credit card
4.3. SuiteFourCaseThree:Add products to shopping cart and make
payment using Cash On Delivery
Note: If SuiteFourCaseTwo only need to be tested, this test can be
enabled through excel file by mentioning 'y' in the TestSuiteList.xls for
SuiteFour and 'y' for this particular test in SuiteFour.xls

Reference:
 Aravind. (2016, September 07). Software testing tutorials and
automation [Web log post]. Retrieved from http://www.software-
testing-tutorials-automation.com/p/selenium-WebDriver.html

115

Author Copy. Not For Distribution.


Narayanan Palani

 Syam. (2015, January 29). XLS Reading for DDF [Web log post].
Retrieved from http://pssqtp.blogspot.co.uk/2015/01/xls-reading-
for-ddf.html
 zhaozhiwen (2016, June 16). 手把手教你搭建数据驱动测试框架
[Web log post]. Retrieved from
http://www.jianshu.com/p/206654aeae29

Maintaining Object Repositories and Reusable Components


This section continuous to refer to the script from TestSuiteBase.java as
the object repositories/reusable components can be developed and
placed within this java file for better reusability.

Reference:
 https://github.com/narayananpalani/testautomation/tree/master/SAF/s
rc/com/stta/TestSuiteBase
Where you can find this file in framework:
 SAF\src\com\stta\TestSuiteBase
 File Name: SuiteBase.java
 Coding Style: Java Programming

Automation Frameworks are compared and evaluated based on the


perfect maintenance of objects within their repositories and ease of use
on their shared objects. This can be best understood by examples:
Assume that the following line of script required within
SuiteOneCaseOne in order to click on a question within the web page:
driver.findElement(By.id("hint_question_id")).click();
hint_question_id is the object and click event performing click event
on top of this object; If there are four different tests within the
framework need this line of code, we can simply copy and then paste to
those java files. Assume if there is a need of writing this code within
eighty test scripts and tester copy pastes the line eighty times and then
the object id changes from hint_question_id to hint_question_ID01 in the
next project cycle then what will be the consequences?
To avoid continuous repetitions, hint_question_id can be maintained
within object.properties file and it can be edited only once when there are
id changes to the object which will get reflected in rest of the automation
framework without even touching the line of codes.
Assuming that the project developers decided to change the question
to be a text box and expected to get an input from users hence the code
will change to the below:

116

Author Copy. Not For Distribution.


Selenium Webdriver

driver.findElement(By.id("hint_question_id ")).sendKeys("what is your


date of birth");
This change will result in manual amend of the script in eighty test
files and it has to be reviewed once amended. If we need to avoid this
repetitive work of code amendments, we need to maintain reusable
components using following steps:

Step1:Navigate to object.properties and insert the line below:


btn_question=//input[@id=' hint_question_id ']

Step2:Replace this line of code in SuiteOneCaseOne:


Change the script from:
driver.findElement(By.id("hint_question_id")).click();
Change the script to: WebElementClick(btn_question);
Note: Update the line above to all the relevant scripts, so the changes to
id or click event can be updated simply by updating one line of
code(instead multiple lines in every test file)

Step3: Insert the below function in TestSuiteBase.java:


public SAF_WebElementClick(String Key){
try{
return driver.findElement(By.id(Object.getProperty(Key))) .click();
}catch(Throwable t){
Add_Log.debug("Object not found for key or not ready--"+Key);
return null;
}

Step4: When the click event getting changed in the project to user inputs
based text box, tester is required to update just one line in the function
below:
public WebElementClick(String Key){
try{
return driver.findElement(By.id(Object.getProperty(Key))) .
sendKeys("what is your date of birth");
}catch(Throwable t){
Add_Log.debug("Object not found for key or not ready--"+Key);
return null;
}

117

Author Copy. Not For Distribution.


Narayanan Palani

How it is getting benefited to the overall project in long run?


 Example-before implementing the 'Reusable Components' and
'Object Repositories':
Stephen writes the automation framework and he just followed writing
object ids and scripts straight to the code of each tests and there were
total of two hundred tests within the framework; Jonathan changes the id
of this object in next sprint (within the agile project) to align with the
naming standards of objects and this change result in changing 200 line
of codes by Stephen which took nearly 2 MANDAYS to complete and
rerun the test execution. During this period, test execution is stopped
hence 2MANDAYS+2 Day execution schedule has been affected.

 Example-before implementing the 'Reusable Components':


Stephen writes the automation framework and he just followed writing
object ids and scripts straight to the code of each tests and there were
total of two hundred tests within the framework; Jonathan changes the id
of this object in next sprint (within the agile project) to align with the
naming standards of objects and this change result in changing just one
line within param.properties file as Stephen already implemented object
properties concept and thus the rework is absolutely zero!

 Example-after implementing the 'Reusable Components' and


'Object Repositories':
Stephen writes the automation framework and he just followed writing
object ids and scripts straight to the code of each tests and there were
total of two hundred tests within the framework; Jonathan changes the id
of this object along with changes to the type of this element (from button
to text box) in next sprint (within the agile project) to align with the
naming standards of objects and this change result in changing just one
line within param.properties file and changing the click event to
sendkeys event within reusable component as Stephen already
implemented object properties and reusable components concept and
thus the rework is absolutely zero!
Below are the line of scripts written in TestSuiteBase file to
maintain the reusable components with their reference to Object
Repositories (using param.properties) :
Note: These 'Reusable Components' can be reused across different
projects once developed. Also maintaining such huge repositories help
developing 'high end' automation frameworks for the organizations to
redeploy in any new testing projects without any major changes to the
automation framework code.

118

Author Copy. Not For Distribution.


Selenium Webdriver

Reference:
 Aravind. (2016, September 07). Software testing tutorials and
automation [Web log post]. Retrieved from http://www.software-
testing-tutorials-automation.com/p/selenium-WebDriver.html
 Syam. (2015, January 29). XLS Reading for DDF [Web log post].
Retrieved from http://pssqtp.blogspot.co.uk/2015/01/xls-reading-
for-ddf.html
 zhaozhiwen (2016, June 16). 手把手教你搭建数据驱动测试框架
[Web log post]. Retrieved from
http://www.jianshu.com/p/206654aeae29

Data Driven Framework -Step by Step Instructions


Test automation frameworks are designed with excel file based test data
to send and perform actions during test execution.xls and xlsx type excel
files are widely used to store data to send user inputs and store test
execution outputs. This section explains the basics on how to design such
basic selenium WebDriver based automation framework using excel
files.
Navigate to Apache POI project to download necessory jar files for
reading the data from excel files:
http://poi.apache.org/download.html

Figure 75 Download Apache POI Files

Download the zip file and extract all to a local file folder.
Launch Eclipse:

119

Author Copy. Not For Distribution.


Narayanan Palani

Figure 76 Launch Eclipse

Choose the Workspace (or create a new location to be the workspace for
this test):

Figure 77 Workspace Launcher

Create a new Java Project as below:


File>New>Java Project

Figure 78 Create New Java Project

120

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 79 Create New Java Project


Right click on the project and navigate to configure project build path:

121

Author Copy. Not For Distribution.


Narayanan Palani

Figure 80 Configure Build Path

Add external JARs into Libraries (which are recently downloaded):

Figure 81 Java Build Path- Libraries Tab

122

Author Copy. Not For Distribution.


Selenium Webdriver

Step1:

Figure 82 Select files from downloaded


Apache POI extracted folder

Step2-Lib based Jar files:

Figure 83 Select files from downloaded


Apache POI extracted folder

123

Author Copy. Not For Distribution.


Narayanan Palani

Step3-ooxml-lib based jar files:

Figure 84 Select files from downloaded


Apache POI extracted folder

Once added, they appear in the libraries list:

Figure 85 JAR files added to libraries

124

Author Copy. Not For Distribution.


Selenium Webdriver

Click on OK and move to src folder. Right click on src folder to create a
package:

Figure 86 Create Package

Figure 87 Create Package

Once Package is created, create a java class file (main test file) in the
name ExcelDataCheckTest.java:

Figure 88 Crate Class File

125

Author Copy. Not For Distribution.


Narayanan Palani

ExcelDataCheckTest.java file look like the below code snippet:

Figure 89 Class File Created

Import below set of files which are originally configured to the project
path through jar files:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Current set of code in the project test file:

Figure 90 Import Section

Create a folder within the project and call it as 'ExcelFolder':

126

Author Copy. Not For Distribution.


Selenium Webdriver

Once created, right click and go to properties to see the path of the file
and open it in windows and create TestInput.xlsx data file:

Figure 91 Excel File Folder Location

Rename the first sheet of the file as TestSheet1:

Figure 92 Sheet Name within Excel File

Update the test data as the below sample texts:

Figure 93 Data Written in Excel File for the Tests

Update the test scripts within the class file:

Figure 94 Script Location

127

Author Copy. Not For Distribution.


Narayanan Palani

public void ReadExcel(String filePath,String fileName,String


sheetName,String[] dataToWrite) throws IOException{
//File class object is initiated to open xlsx based data file
File file = new
File("E:\\AutomationProject\\Training\\DataDrivenFramework\\ExcelFol
der\\TestInput.xlsx"); //FileInputStream class initiated to read excel data
file
FileInputStream inputStream = new FileInputStream(file);
}

Main section of code:


Place the code logic below at the location marked in screenshot:

Figure 95 Script Location

Code:
Workbook sampleExcel = null;
//These lines are splitting the file name from extension to understand
what filetype the excel based on? (either xls or xlsx)
String extType = fileName.substring(fileName.indexOf("."));
//Check if xlsx file
if(extType.equals(".xlsx")){
//If it is xlsx file ,following class has to be created:
sampleExcel = new XSSFWorkbook(inputStream);
}

128

Author Copy. Not For Distribution.


Selenium Webdriver

//Check if xls file


else if(extType.equals(".xls")){
//If it is xls file ,following class has to be created:
sampleExcel = new HSSFWorkbook(inputStream);
}
//This step is required to read the sheet name within the excel file:
Sheet winexcelSheet = sampleExcel.getSheet(sheetName);
//Find number of rows in excel file
int numberOfRows = winexcelSheet.getLastRowNum()-
winexcelSheet.getFirstRowNum();
//Read the excel data from a loop:
for (int a = 0; a < numberOfRows+1; a++) {
Row row = winexcelSheet.getRow(a);
//Print the data using a loop
for (int b = 0; b < row.getLastCellNum(); b++) {
//Print data in console output to read and understand how it is executed
System.out.print(row.getCell(b).getStringCellValue()+"|| ");
}
System.out.println();
}

Complete Set of Code once the script are up-to-date:


package dataValidationPack;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDataCheckTest {
public void ReadExcel(String filePath,String fileName,String
sheetName,String[] dataToWrite) throws IOException{
//File class object is initiated to open xlsx based data file

129

Author Copy. Not For Distribution.


Narayanan Palani

File file = new


File("E:\\AutomationProject\\Training\\DataDrivenFramework\\ExcelFol
der\\TestInput.xlsx");
//FileInputStream class initiated to read excel data file
FileInputStream inputStream = new FileInputStream(file);
Workbook sampleExcel = null;
//These lines are splitting the file name from extension to understand
what filetype the excel based on? (either xls or xlsx)
String extType = fileName.substring(fileName.indexOf("."));
//Check if xlsx file
if(extType.equals(".xlsx")){
//If it is xlsx file ,following class has to be created:
sampleExcel = new XSSFWorkbook(inputStream);
}
//Check if xls file
else if(extType.equals(".xls")){
//If it is xls file ,following class has to be created:
sampleExcel = new HSSFWorkbook(inputStream);
}
//This step is required to read the sheet name within the excel file:
Sheet winexcelSheet = sampleExcel.getSheet(sheetName);
//Find number of rows in excel file
int numberOfRows = winexcelSheet.getLastRowNum()-
winexcelSheet.getFirstRowNum();
Read the excel data from a loop:
for (int a = 0; a < numberOfRows+1; a++) {
Row row = winexcelSheet.getRow(a);
//Print the data using a loop
for (int b = 0; b < row.getLastCellNum(); b++) {
//Print data in console output to read and understand how it is executed
System.out.print(row.getCell(b).getStringCellValue()+"|| ");
}
System.out.println();
}
}
}

Next Step:
This ReadExcel class has to be called in any main function and use the
test data into the main program.
130

Author Copy. Not For Distribution.


Selenium Webdriver

Sample Code for example:


package dataValidationPack;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import pomfunctions.LoginPOM;
public class ExcelDataCheckTest {
public void ReadExcel(String filePath,String fileName,String
sheetName) throws IOException{
//File class object is initiated to open xlsx based data file
File file = new
File("E:\\AutomationProject\\Training\\DataDrivenFramework\\ExcelFol
der\\TestInput.xlsx");
//FileInputStream class initiated to read excel data file
FileInputStream inputStream = new FileInputStream(file);
Workbook sampleExcel = null;
//These lines are splitting the file name from extension to understand
what filetype the excel based on? (either xls or xlsx)
String extType = fileName.substring(fileName.indexOf("."));
//Check if xlsx file
if(extType.equals(".xlsx")){
//If it is xlsx file ,following class has to be created:
sampleExcel = new XSSFWorkbook(inputStream);
}
//Check if xls file
else if(extType.equals(".xls")){
//If it is xls file ,following class has to be created:
sampleExcel = new HSSFWorkbook(inputStream);

131

Author Copy. Not For Distribution.


Narayanan Palani

}
//This step is required to read the sheet name within the excel file:
Sheet winexcelSheet = sampleExcel.getSheet(sheetName);
//Find number of rows in excel file
int numberOfRows = winexcelSheet.getLastRowNum()-
winexcelSheet.getFirstRowNum();
//Read the excel data from a loop:
for (int a = 0; a < numberOfRows+1; a++) {
Row row = winexcelSheet.getRow(a);
//Print the data using a loop
for (int b = 0; b < row.getLastCellNum(); b++) {
//Print data in console output to read and understand how it is executed
System.out.print(row.getCell(b).getStringCellValue()+"|| ");
}
System.out.println();
}
}
private static WebDriver driver = null;
public static void main(String[] args)throws IOException{
System.setProperty("WebDriver.chrome.driver","E://AutomationProject/
/Training//SalesforceTestAutomation//BrowserDrivers//chromedriver.ex
e");
driver = new ChromeDriver();
driver.get("https://login.salesforce.com");
ExcelDataCheckTest objExcel=new ExcelDataCheckTest();
String fileLocation =
System.getProperty("E:\\AutomationProject\\Training\\DataDrivenFram
ework\\ExcelFolder\\TestInput.xlsx");
objExcel.ReadExcel(fileLocation, "TestInput.xlsx", "TestSheet1");
LoginPOM.txt_sfusername(driver).sendKeys("Narayanan@narayanan.co
m");
LoginPOM.txt_sfpwd(driver).sendKeys("HelloWorld");
LoginPOM.btn_sfLogin(driver).click();
driver.quit();
}
}

Expalanation: Following set of three line code call the entire test data
input class file (called ReadExcel) and take the test inputs:
ExcelDataCheckTest objExcel=new ExcelDataCheckTest();
132

Author Copy. Not For Distribution.


Selenium Webdriver

String fileLocation =
System.getProperty("E:\\AutomationProject\\Training\\DataDrivenFram
ework\\ExcelFolder\\TestInput.xlsx");
objExcel.ReadExcel(fileLocation, "TestInput.xlsx", "TestSheet1");

If this test is getting executed, following are console output displayed:

Figure 96 Test Execution Results

Test excel sheet's user inputs are taken into the main class and
successfully printed!
Note: JXL API is not used in the test example above as it is not
supported to get data inputs from xlsx based data files.
Data inputs (to test execution) to feed as user inputs and data
outputs(from test execution) of test results to excel files are explained in
the next section.

Reference:
 Guru99. (2016, September 22), All About Excel in Selenium: POI &
JXL [Web log post]. Retrieved from http://www.guru99.com/all-
about-excel-in-selenium-poi-jxl.html

Data Driven Tests using Excel Files with Selenium Web Driver
This section explains how the excel file based test data are used within
the automation framework and one of the key section for Data Driven
Framework Design.
Knowing the fact that Selenium WebDriver doesn't support excel
based test data directly and this challenge can be rectified by writing
class files to get excel files talk to Selenium based Automation
Framework.
JXL library is used for data driven testing framewrowks to provide
classes and methords and interact with excel files in xls format.If Apache
POI library has been used, tester can access xls or xlsx within the project.

133

Author Copy. Not For Distribution.


Narayanan Palani

 Reference:
https://github.com/narayananpalani/testautomation/tree/master/SAF/s
rc/com/stta/utility
 Where you can find this file in framework: SAF\src\com\stta\utility
 File Name: Read_XLS.java
 Coding Style: Java Programming

Location of the file:

Figure 97 Excel Files for the Tests

If there is an exception in opening the particular excel file, the


following commands print exceptions within the log files using catch
statement.
To retrieve No Of Rows from .xls file's sheets-this
retrieveNoOfRows determines how many rows to run the auto tests. If the
test data are written for 300 rows, the test has to be repeated that many
times. So automation framework capture the sheetindex when the data
are written using retrieveNoOfRows function.

Example:

Figure 98 Data Input Available from Excel File

Tests should be skipped if 'n' mentioned in DataToRun column-Example:

Figure 99 Data to Run Column to write y for Yes and n for No

134

Author Copy. Not For Distribution.


Selenium Webdriver

To retrieve test data from test case data sheets 'retrieveTestData'


function is used. RetrieveTestData acts as an array to capture the test
data from excel file and then used to feed in the WebDriver.

Example:

Figure 100 First Row of the Data from Excel File

If the test input is unsupported, it capture and update runtime


exception to tester to correct the data using the scripts ' cellToString'.
To write result In test data and test case list sheet ' writeResult'
scripts are written. When test inputs are taken from excel files, testers
need to know respective row of tests passed or not. Also how many rows
are executed and how many or not executed. If there are hundreds of test
data rows, it has to be clearly updated once the test is completed or
aborted. Lines of scripts in ' writeResult' update the test data rows every
time it completes a row and move to next row.

Example:

Figure 101 Test Output/Results saved to Excel File

To write result In test suite list sheet ' writeResult' scripts are written.
Basically test automation frameworks are expected to get the inputs from
test excel files and then return the results after testing the application to
the same excel files or different excel files based on the need. In this
automation framework, test results are updated in the same excel files
with PASS/FAIL status to clarify whether the tests are execute, passed or
failed. In the script of ' writeResult', it is updating the results of Suites
(not the test cases):

Example:

Figure 102 WriteResult Example


135

Author Copy. Not For Distribution.


Narayanan Palani

In case of any exceptions during the process of data inputs to excel


from automation framework, it has to be captured and notified. Catch
function is used to exactly catch and print the stack traces for tester's
benefit in last few lines of the scripts.

Reference:
 Aravind. (2016, September 07). Software testing tutorials and
automation [Web log post]. Retrieved from http://www.software-
testing-tutorials-automation.com/p/selenium-WebDriver.html
 Syam. (2015, January 29). XLS Reading for DDF [Web log post].
Retrieved from http://pssqtp.blogspot.co.uk/2015/01/xls-reading-
for-ddf.html
 zhaozhiwen (2016, June 16). 手把手教你搭建数据驱动测试框架
[Web log post]. Retrieved from
http://www.jianshu.com/p/206654aeae29

Capture Screenshots using Selenium WebDriver


This section primarily explains about how the screenshot capability can
be extended to selenium WebDriver using ITestListener, ITestContext,
ITestResult within your test script.Screenshots are the test evidences or
the proofs that the test has been conducted. Testers always update the
test results to test manager but there is a proof like screenshot required
in order to verify the overall results.

Need for screenshots:


Software testers tests the application and if some or many of the
functionalities are not working (comparing to expected results)then
testers log defects and suggest developers to investigate on why the
defect has occurred and get it fixed in order to retest once again; But
developers never accept a defect straightaway without required evidences
and details which are needed to analyse about the issues. In website
based testing, getting screenshot is one of the mandatory evidence to
view the screen in image file (like jpg or jpeg or png) to understand what
went wrong. Though manual testers take screenshots and save it with
tests during execution, many auto testers save test results using different
automation tools used within projects hence it is not necessary that the
tool take the screenshot for every test. But it is tester's responsibility to
make sure that the evidences are taken as screenshots hence automation
frameworks should support taking screenshots.

136

Author Copy. Not For Distribution.


Selenium Webdriver

How the Screenshot Utility can be extended to Selenium based


Framework?
One of the great functionality within TestNG is to enable the screenshot
capture capability (which need to be extended with different tools if tests
are executed from Junit). This is one of the primary reason why test
experts choose to opt in the combination of Selenium WebDriver with
TestNG when designing the automation frameworks. ITestListener from
TestNG can extend to selenium framework and then the screenshots from
web applications are listened and captured within seconds and stored in
the locations described in test scripts (see the scripts in this section)

Reference:
 https://github.com/narayananpalani/testautomation/tree/master/SAF/s
rc/com/stta/utility
 Where you can find this file in framework: SAF\src\com\stta\utility
 File Name: ScreenshotUtility.java
 Coding Style: Java Programming

As part of the test execution, file has to be created to capture screen of


the web application being tested. So the following file has been imported
from io of java package:
import java.io.File;

Exceptions are handled using IOException in case of error in accessing


the target location to create a screenshot file or error in accessing the
website due to access block either at website or at file location:
import java.io.IOException;

It is suggested to update the screenshot with date,time and seconds which


is possible through following import:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;

In order to handle output file types such as jpeg,jpg or other


formats,OutputType has been imported:
import org.openqa.selenium.OutputType;

137

Author Copy. Not For Distribution.


Narayanan Palani

Primary logic of screen capture during test execution is handled by


TakesScreenshot from selenium; Though ITestListener has to help to
save the files, TakesScreenshot is the core concept of Selenium to take
the full shot of the web screen which is imported below:
import org.openqa.selenium.TakesScreenshot;

Following three important elements are imported from TestNG jar file to
support screenshot capture:
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

ScreenshotUtility get the capability of TestNG methods for screenshot


utility using below script:ScreenshotUtility
This method will execute before starting of Test suite:onStart
This method will execute, Once the Test suite is finished:onFinish
This method will execute only when the test is passed. So the test's
screenshot will be saved in Success Folder in the automation
framework:onTestSuccess

Example:

Figure 103 Screenshots of Passed Tests

This method will execute only on the event of fail test and get it saved in
Failure folder within automation framework:onTestFailure

Example:

Figure 104 Screenshot of Failed Tests

138

Author Copy. Not For Distribution.


Selenium Webdriver

This method will execute before the main test start (see '@Test'
within suiteonecaseone java file for example); So it takes control of the
test and receive test result:onTestStart
This method will execute only if any of the main test(@Test) get
skipped:onTestSkipped
Following lines are the main function to capture screenshot and
name it with date,time and then save in the location:captureScreenShot
To capture screenshot:File scrFile
Following is the format in which name suffix getting updated hence
tester can pick up right screenshot based on timings: dateFormat

Example:

Figure 105 Screenshot Folders within Automation Framework

XSLT Reporting
The best part of Selenium-TestNG based automation framework is that
the reporting can be extended as html email-able reports using XSLT
reporting! This can be done simply by using xsl file ' testng-results.xsl'.
Reference:
 https://github.com/narayananpalani/testautomation/tree/master/SAF/s
rc/com/stta/xslt
 Where you can find this file in framework: SAF\src\com\stta\xslt
 File Name: testng-results.xsl
 Coding Style: XSL Programming

When tests are getting executed,reports can be accessed from the file:
test-output folder
Example in Git folders:
https://github.com/narayananpalani/testautomation/blob/master/SAF/test-
output/emailable-report.html

139

Author Copy. Not For Distribution.


Narayanan Palani

Example XSLT report

Figure 106 XSLT Report

How to add such XSLT Reports to the emails and send to


stakeholders?
Launch Outlook and click on New Email Message to write a new email:

Figure 107 New Email from MS Outlook

Select test-output folder of the automation framework where the


emailable-report.html is generated after test execution by XSLT reports:

140

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 108 Locate Test Results (Test Output) Folder

Click on the HTML file and select the type as 'Insert as Text':

Figure 109 Select Test Results File

Choose Insert as Text:

Figure 110 Select Insert as Text

141

Author Copy. Not For Distribution.


Narayanan Palani

When the test results added as text, it convert the email with html test
results within the message section:

Figure 111 Insert As Text result in adding the HTML Test Results
within Email Content

Parameterization in Automation Framework


The basic concept of parameterization is dated back to starting time of
web development and implemented to software test scripts to have better
maintenance and reduced rework. In the automation framework, we can
maintain web URLs, configuration settings (any options to turn setting
ON or OFF),types of test needs such as which browser test has to run or
which test environment test has to get executed etc. This kind of
parameterization will benefit manual testers to execute the automation
scripts as and when required.
 How to get the parameterization concept within framework?
Step1: Open SuiteBase.Java and refer the object:Param
These lines take the properties directly from param.properties and feed
into test scripts.

142

Author Copy. Not For Distribution.


Selenium Webdriver

Step2: Open the folder SAF\src\com\stta\property and place


param.properties with below description:
#Web Application URL
siteURL=http://abc.com
#set Mozilla or Chrome or IE
testBrowser=Chrome
#Set Screenshot flags "Yes" or "No"
screenShotOnFail=Yes
screenShotOnPass=Yes

These lines given above are samples and it can be condensed with
multiple test environment details such as:
#Web Application URL
TestEnvironment1_URL=http://abc.com
TestEnvironment2_URL=http://def.com
TestEnvironment3_URL=http://ghi.com
#set Mozilla or Chrome or IE7 or IE8 or IE9 or Opera
testBrowser=Chrome
#Set Screenshot flags "Yes" or "No"
screenShotOnFail=Yes
screenShotOnPass=Yes

Step3: When test has to be executed, amend param file with respective
settings such as browser, url and other details to compile and run the
project.

 How the script works to capture respective test settings from


param file?
"loadWebBrowser();" from SuiteOneCaseOne.java calls the function
loadWebBrowser() which is placed in SuiteBase.Java and then this
function takes the property from param file through "Param.getProperty".
For example, if driver is Chrome then the script refers to the below line
and launch driver exe file:
System.setProperty("WebDriver.chrome.driver",
System.getProperty("user.dir")+"//BrowserDrivers//chromedriver.exe");

Note: There are two types of browser exes such as 32 bit and 64 bit; If
incorrect exe file is placed in 'BrowserDrivers' folder then the test will be
very slow; Always verify target machine's system property (32 bit or 64

143

Author Copy. Not For Distribution.


Narayanan Palani

bit) and choose respective exe file of browser and place it in


'BrowserDrivers' folder.

TestNG Scripting for Selenium Automation Framework


TestNG is installed in the automation framework and the instructions are
available in the Part1 of this book. This section explains on instructions
to build basic TestNG xml file
TestNG.xml file acts as a configuration file with test suites and tests
included for test execution in which parameters are passed to test
methods; Suite Name is specified in top of the xml file with suite tag
and then list of tests are specified within test tags.

Example-Two tests are included in the TestNG xml file called


SuiteOne.xml:
<?xml version="1.0" encoding="UTF-8"?>
<suite name="SuiteOne">
<!--add the list of test cases from the test suites below. -->
<test name="SuiteOneCaseOne">
<classes>
<class name="com.stta.SuiteOne.Place the class name of the test"
></class>
</classes>
</test>
<test name="SuiteOneCaseTwo">
<classes>
<class name="com.stta.SuiteOne. Place the class name of the tes"
></class>
</classes>
</test>
</suite>

How to design set of TestNG files for the below scenario?


Test SuiteBase: Shopping Cart
4. Suite One: Login
4.4. SuiteOneCaseOne: Login with valid user id and password of
customers using Chrome
4.5. SuiteOneCaseTwo: Login with valid admin id and password of
Administrator using IE7
5. SuiteTwo:Add to Shopping Cart

144

Author Copy. Not For Distribution.


Selenium Webdriver

5.1. SuiteTwoCaseOne: Add one product to shopping cart using


Firefox
5.2. SuiteTwoCaseTwo:Add multiple products to shopping cart
using Chrome
5.3. SuiteTwoCaseThree:Add multiple products to shopping cart
and delete multiple products from shopping cart using IE8
5.4. SuiteTwoCaseFour:Add products to shopping cart,logout and
login to validate the products added to shopping cart in earlier
session using Firefox

TestNG Files:
File1: SuiteOne.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--SuiteOne:Login -->
<suite name="SuiteOne">
<!-- SuiteOneCaseOne: Login with valid user id and password of
customers using Chrome-->
<test name="SuiteOneCaseOne">
<classes>
<class name="com.stta.SuiteOne.SuiteOneCaseOne" ></class>
</classes>
</test>
<!-- SuiteOneCaseTwo: Login with valid admin id and password of
Administrator using IE7-->
<test name="SuiteOneCaseTwo">
<classes>
<class name="com.stta.SuiteOne.SuiteOneCaseTwo" ></class>
</classes>
</test>
</suite>

File2: SuiteTwo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- SuiteTwo:Add to Shopping Cart-->
<suite name="SuiteTwo">
<!-- SuiteTwoCaseOne: Add one product to shopping cart using Firefox-
->
<test name="SuiteTwoCaseOne">
<classes>
<class name="com.stta.SuiteOne. SuiteTwoCaseOne " ></class>

145

Author Copy. Not For Distribution.


Narayanan Palani

</classes>
</test>
<!-- SuiteTwoCaseTwo:Add multiple products to shopping cart using
Chrome-->
<test name="SuiteTwoCaseTwo">
<classes>
<class name="com.stta.SuiteOne. SuiteTwoCaseTwo " ></class>
</classes>
</test>
<!-- SuiteTwoCaseThree:Add multiple products to shopping cart and
delete multiple products from shopping cart using IE8-->
<test name="SuiteTwoCaseThree">
<classes>
<class name="com.stta.SuiteOne. SuiteTwoCaseThree " ></class>
</classes>
</test>
<!-- SuiteTwoCaseFour:Add products to shopping cart,logout and login
to validate the products added to shopping cart in earlier session using
Firefox-->
<test name="SuiteTwoCaseFour">
<classes>
<class name="com.stta.SuiteOne.SuiteTwoCaseFour " ></class>
</classes>
</test>
</suite>

File3:testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Calc Suite">
<!-- Enter the listeners such as ScreenshotUtility,QC Integration
Utility,Defect Raising Utility in the section below-->
<listeners>
<listener class-name="com.stta.utility.ScreenshotUtility"></listener>
</listeners>
<!-- Enter the list of TestNG xml files in this section below;Those test
xml files will be called from this file and respective tests from those files
will get executed through this single file-->
<suite-files>
<suite-file path="./SuiteOne.xml" />
<suite-file path="./SuiteTwo.xml" />
146

Author Copy. Not For Distribution.


Selenium Webdriver

</suite-files>
</suite>

How to get the TestNG files to execute Selenium scripts?


Navigate to test-output folder, right click on the TestNG xml file,click on
Run As and click TestNG Suite:

Figure 112 Execute the Tests using TestNG

Note: If TestNG is not installed to the framework, tester won't get the
TestNG logo in this list of options.

Run the tests alternatively from Command Prompt:


java -cp "/opt/testng-6.8.5.jar:bin" org.testng.TestNG testng.xml
Note: edit the TestNG version based on the jar file placed in the
automation framework location: \SAF\JarFiles

Parallel Test Execution using TestNG


Due to time limitations at test execution, most of the testing teams look
for parallel test execution as one of the option from testing tools. This is
possible and available from TestNG. It can be enabled by adding
parallel=classes to select multiple classes to run in parallel within
TestNG as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!--SuiteOne:Login -->

147

Author Copy. Not For Distribution.


Narayanan Palani

<suite name="SuiteOne" parallel="classes" thread-count="2">


<!-- SuiteOneCaseOne: Login with valid user id and password of
customers using Chrome-->
<test name="SuiteOneCaseOne">
<classes>
<class name="com.stta.SuiteOne.SuiteOneCaseOne" ></class>
</classes>
</test>
<!-- SuiteOneCaseTwo: Login with valid admin id and password of
Administrator using IE7-->
<test name="SuiteOneCaseTwo">
<classes>
<class name="com.stta.SuiteOne.SuiteOneCaseTwo" ></class>
</classes>
</test>
</suite>

TestNG Annotations
While using Selenium WebDriver based java test automation
frameworks, TestNG has been added to configure and execute test suites
and test cases within the framework build. So entire selenium based tests
are executed from TestNG xml files. Certain annotations are used in
TestNG similar to JUnit and this section provide sample code snippets
for some of the popular annotations of TestNG.

Case1:
In order to execute a particular web based test, browser has to be
launched and url has to be updated on the browser- @BeforeTest of
TestNG can be used to perform these actions in every tests.Proper tests
can be scripted under the annotation @Test of TestNG; Similarly once
the test has been executed, browser has to be closed and this action can
be scripted in @AfterTest annotation based section.

Sample Code:
In the test described below, web page getting launched with respective
url using @BeforeTest annotation of TestNG and @Test section getting
executed and then the final section @AfterTest is getting executed.
package junitreporttestpackage;
import java.io.IOException;
import org.openqa.selenium.By;

148

Author Copy. Not For Distribution.


Selenium Webdriver

import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Dropdowntesting {


System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PRO
PERTY,"E://AutomationProject//Training//SFS//BrowserDrivers//gecko
driver.exe");
WebDriver driver = new FirefoxDriver();
Wait<WebDriver> wait=new WebDriverWait(driver,30);
@BeforeTest
public void beforetest() {
driver.get("http://www.yahoo.com");
driver.manage().window().maximize();
}
@Test
public void test () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Cars")));
drpdwn.selectByVisibleText("Lambogini");
}
@AfterTest
public void aftertest() {
driver.quit();
}
}

Execution:
Run the tests and observe the console output for this test.
@BeforeTest section executed
@Test section executed
@AfterTest section executed

149

Author Copy. Not For Distribution.


Narayanan Palani

Case2:
Perform the same set of scripts with more than one test in a given test
execution and validate the outputs.
Sample Code:
package junitreporttestpackage;
import java.io.IOException;
import org.openqa.selenium.By;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Dropdowntesting {


System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PRO
PERTY,"E://AutomationProject//Training//SFS//BrowserDrivers//gecko
driver.exe");
WebDriver driver = new FirefoxDriver();
Wait<WebDriver> wait=new WebDriverWait(driver,30);
@BeforeTest
public void beforetest() {
driver.get("http://www.yahoo.com");
driver.manage().window().maximize();
}
@Test
public void SampleTest1 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));
drpdwn.selectByVisibleText("KSRTC");
}
@Test
public void SampleTest2 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));

150

Author Copy. Not For Distribution.


Selenium Webdriver

drpdwn.selectByVisibleText("APSRTC");
}

@AfterTest
public void aftertest() {
driver.quit();
}
}

Execution:
Run the tests and observe the console output for this test.
@BeforeTest section executed
@Test section executed for SampleTest1
@AfterTest section executed
@BeforeTest section executed
@Test section executed for SampleTest2
@AfterTest section executed

Challenge: It is time consuming to kill the browser once test1 is


completed using @AfterTest and launch once again using @BeforeTest
before @Test of next test; In order to avoid this unnecessary repetition,
@BeforeClass and @AfterClass can be used.

Case2 Revised Version:


Sample Code:
package junitreporttestpackage;
import java.io.IOException;
import org.openqa.selenium.By;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Dropdowntesting {

151

Author Copy. Not For Distribution.


Narayanan Palani

System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PRO
PERTY,"E://AutomationProject//Training//SFS//BrowserDrivers//gecko
driver.exe");
WebDriver driver = new FirefoxDriver();
Wait<WebDriver> wait=new WebDriverWait(driver,30);
@BeforeClass
public void beforetest() {
driver.get("http://www.yahoo.com");
driver.manage().window().maximize();
}
@Test
public void SampleTest1 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));
drpdwn.selectByVisibleText("KSRTC");
}
@Test
public void SampleTest2 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));
drpdwn.selectByVisibleText("APSRTC");
}

@AfterClass
public void aftertest() {
driver.quit();
}
}

Execution:
Run the tests and observe the console output for this test.
@BeforeClass section executed
@Test section executed for SampleTest1
@Test section executed for SampleTest2
@AfterClass section executed

152

Author Copy. Not For Distribution.


Selenium Webdriver

Note: Similar to @BeforeTest and @BeforeClass, there are few other


useful annotations available to use in different conditions:
@BeforeSuite
@AfterSuite
@BeforeTest
@AfterTest
@BeforeGroups
@AfterGroups
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod

Difference between JUnit and TestNG:


when tests are run using TestNG,respective annotations are imported in
import sections such as
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

In case of JUnit, different (JUnit related imports) files are required:


import org.junit.After;
import org.junit.Before;
import org.junit.Test;

Similarly, @Test used as common across TestNG and Junit, but


@BeforeTest is used as @Before in JUnit; @AfterTest of TestNG is
used as @After in JUnit.

DataProvider Annotation in TestNG


When data has been passed from different array or through excel based
test data sheet, they can be updated to tests using @DataProvider
annotation like the below. In this example, LoginDetails()is the location
where data has been updated for ease of maintenance and it is called to
get the data using (dataProvider="LoginDetails") code in @Test Line:
public class Login {
@Test(dataProvider="LoginDetails")
public void LoginExample(String UserName, String Pwd) {

153

Author Copy. Not For Distribution.


Narayanan Palani

driver.findElement(By.type("userID")).sendKeys(UserName);
driver.findElement(By.type("Password")).sendKeys(Pwd);
driver.findElement(By.type("LoginButton")).Click();
}
@DataProvider
public Object[][] LoginDetails() {
return new Object[][]{{"Narayanan"}, {"HelloWorld"}};
}
}

TestNG Test Case Priority


Most of the automation test projects designed with test cases based on
priorities and always high priority test cases are taking business
importance and some special cases, testers are requested to run atleast
high priority tests to validate the functional stability. In order to
facilitate this feature within TestNG based tests (priority=) section is
used to highlight the test case priority.

Let us take an example of four test cases with different priorities:


package testngreporttestpackage;
import java.io.IOException;
import org.openqa.selenium.By;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Dropdowntesting {
System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PRO
PERTY,"E://AutomationProject//Training//SFS//BrowserDrivers//gecko
driver.exe");
WebDriver driver = new FirefoxDriver();
Wait<WebDriver> wait=new WebDriverWait(driver,30);
@BeforeClass
public void beforetest() {
driver.get("http://www.yahoo.com");
driver.manage().window().maximize();

154

Author Copy. Not For Distribution.


Selenium Webdriver

}
@Test(priority=3)
public void SampleTest1 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));
drpdwn.selectByVisibleText("KSRTC");
}
@Test(priority=2)
public void SampleTest2 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));
drpdwn.selectByVisibleText("TNSTC");
}
@Test
public void SampleTest3 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));
drpdwn.selectByVisibleText("APSRTC");
}
@Test(priority=1)
public void SampleTest4 () throws InterruptedException
{
//Selecting value from drop down using visible text
Select drpdwn = new Select(driver.findElement(By.id("Bus")));
drpdwn.selectByVisibleText("MHRTC");
}
@AfterClass
public void aftertest() {
driver.quit();
}
}

Execution:
Run the tests and observe the console output for this test.
@BeforeClass section executed
@Test section executed for SampleTest3

155

Author Copy. Not For Distribution.


Narayanan Palani

@Test section executed for SampleTest4


@Test section executed for SampleTest2
@Test section executed for SampleTest1
@AfterClass section executed

Justifications: Since SampleTest3 is provided with no priority, it is


prioritized high by default and getting executed first (after beforeclass)
and followed by other tests based on 1,2 and 3 priorities.

Reference:
 TestNG (2016 September22)Annotations [Web log post]. Retrieved
from http://testng.org/doc/documentation-main.html#annotations
 Aravind (2016 September22)Example Of Difference Between
@Before/@After VS @BeforeClass/@AfterClass In JUnit With
WebDriver [Web log post]. Retrieved from http://www.software-
testing-tutorials-automation.com/2014/03/example-of-difference-
between.html
 StackOverflow2016 September22)Difference between BeforeClass
and BeforeTest in TestNG [Web log post]. Retrieved from
http://stackoverflow.com/questions/30587454/difference-between-
beforeclass-and-beforetest-in-testng
 Ram Mokkapatty(2015, February28) TestNG DataProvider Example
[Web log post]. Retrieved from
https://examples.javacodegeeks.com/enterprise-java/testng/testng-
dataprovider-example/

Next Generation Test Automation Results Management


Automation Test Execution produces huge set of test results almost every
day and it is huge to create a Data Mart and maintain using ETL
(Extract,Transfer,Load) methods!
But automation frameworks need an intelligent DB to connect and
save the test results for better analysis!
MongoDB is a NoSQL tool to save the test results uisng mongo-
java-driver-2.10.1.jar and it connects to Automation Framework and
saves the test results from TestNG (which handles the test execution of
Selenium WebDriver)
Since the test results are huge in size and need lot of test results to
manage, control and analyse, this particular area is expected to grow
rapidly in near future.

156

Author Copy. Not For Distribution.


Selenium Webdriver

Install MongoDB from the website:


https://docs.mongodb.com/manual/installation/

Script sample:
mongodbconnect.java file within Utility folder of stta within com folder:
Package Name of the file where the java file has been placed is as
follows:
package com.stta.utility;
TestNG has to be installed in the automation framework and use the
following import:
import org.testng.Assert;
Download the mongodb jar file from:
http://grepcode.com/snapshot/repo1.maven.org/maven2/org.mongodb/m
ongo-java-driver/2.10.1
once downloaded,place it in the project folder SAF\JarFiles\

Figure 113 Download Mogo JAR File and


Save in JarFiles Folder

Once placed for backup (to reuse the jar whenever required), bring the
jar file to project build path by:
Right click on the project SAF, Choose Build Path and Configure Build
Path,click on Libraries and click on Add External JARs and finally pick
the mongo JAR file to click OK button:

157

Author Copy. Not For Distribution.


Narayanan Palani

Figure 114 Configure Build Path by adding Mongo JAR file

Once Jar file is added to the project path, following imports are required
to add the files to project:
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;

Class file of the script:


public class MongoDBconnect {
public static void main( String args[] ){
try{

Connecting to the (preinstalled) mongoDB's instance using ip and port


numbers; If IP is not known,try with Localhost:
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

Selecting the database you have created within MongoDB:


DB db = mongoClient.getDB("NameofDB");

158

Author Copy. Not For Distribution.


Selenium Webdriver

Selecting the collection below which is setup in your MongoDB at Test


Environment:
DBCollection dbCollection = db.getCollection("NameOfCollections");

Setting search query with the required key-value pair for example,
testid=23 which means picking the test id from the entire test lists:
BasicDBObject searchQuery = new BasicDBObject();
//searchQuery.put("key", "value");
searchQuery.put("testid", "23");

DBCursor with the find query result which can be select te.error from
test te where te.testid=23:
//DBCursor cursor = dbCollection.find(searchQuery);
DBCursor cursor = dbCollection.find("select te.error from test te where
te.testid=23");

Fetching the response through the script:


String response = null;
try {
while(cursor.hasNext()) {
response = response.concat(cursor.next().toString());
}
}
finally {
cursor.close();
}

Asserting the fetched response using TestNG with expected value :


Assert.assertTrue(response.contains("ExpectedValue"));
}
catch(Exception e)
{ System.out.println(e.getMessage());
}
}
}

Script Reference:
 Hitesh Singh, (2012,August 14), Selenium Web, Mobile Automation
and for Complete Automation Tutorials using WebDriver [Web log
post]. Retrieved from
159

Author Copy. Not For Distribution.


Narayanan Palani

http://silenumnmisc.blogspot.co.uk/2014/08/connection-
between-through-mongodb-and.html
 artoftesting(2016,September24) MongoDB Automation in Java[Web
log post]. Retrieved from
http://artoftesting.com/automationTesting/mongoDBAutomation.
html

Selenium Exceptions Guide


Every automation framework designed to get failed at one point either by
objects or by the configuration of tools implemented; This needs a good
knowledge and reasoning skills to classify whether the failure is due to
application which is tested or the automation framework used for tests.
This section describes about some of the exceptions come up during the
test execution of selenium based frameworks.

How to handle the tests when 'Server Exception : sessionId should


not be null' occurred?
Recommendations:
Try replacing the Chrome Driver xxwith latest version of Chrome
Browser Driver (32 bit or 64 bit based on the machine you get it
installed);

How to Handle ERROR: No sessionId provided?


Suggestions:
If tests are running from hudson, it is not threadsafe hence please see if
jenkins can be used to run the same set of tests.

driver.stop() result in exception-How to fix it?


Recommendations:
If selenium server xxi is closed before this line of code, driver.stop()
which may cause the problem above.

How to handle UnreachableBrowserException?


Recommendation:
If the browser hung continuously or reached the limit of possible open
connections during the test execution, it causes the test failure and
exception in the logsxxii Update the below in Windows Registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpi
p\Parameters
you need to set/create two DWORD values:

160

Author Copy. Not For Distribution.


Selenium Webdriver

MaxUserPort = 32768
TcpTimedWaitDelay = 30

How to handle Illegal state exception using Selenium 3.o beta ?


Code Executed:
package com.sfs.SuiteOne;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class LaunchBrowser {
static WebDriver driver;
public static void main(String[] args){
driver=new FirefoxDriver();
driver.get("www.yahoo.com");
}
}

Figure 115 IllegalStateException thrown during the test execution

Solution: Get the Firefox based Gecko Driver Downloaded from below
link and retry:
https://github.com/mozilla/geckodriver/releases

Figure 116 Download Latest Gecko Driver to run tests in Firefox


Browser when using Selenium 3 onwards

161

Author Copy. Not For Distribution.


Narayanan Palani

How to handle NS_ERROR_FILE_ACCESS_DENIED in Selenium


3.o?
Code Executed:
package com.sfs.SuiteOne;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class LaunchBrowser {
static WebDriver driver;
public static void main(String[] args){
System.setProperty("WebDriver.gecko.driver","E://AutomationProject//
Training//SFS//BrowserDrivers//geckodriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
driver.get("www.yahoo.com");
}
}

Note-Reference link to download the web driver browser:


https://developer.mozilla.org/en-
US/docs/Mozilla/QA/Marionette/WebDriver

Solution: Uninstall the latest version of firefox within target


machine,remove Mozilla Firefox related files in C:Program Files and
then remove Firefox from SOFTWARE section of regedit.

162

Author Copy. Not For Distribution.


Selenium Webdriver

Step1: Uninstall the browser

Figure 117 Firefox Browser Reference

Click Run and type Regedit:

Figure 118 Regedit to open Registry Editor

Click Yes to open Registry Editor like the below:

163

Author Copy. Not For Distribution.


Narayanan Palani

Figure 119 Firefox Browser's folder within Registry Editor

Click on Regedit and navigate to,HKEY_LOCAL_MACHINE and then


SOFTWARE,

Figure 120 Elements within Registry Editor


Choose Mozilla folder and delete it:

Figure 121 Mozilla Folder


164

Author Copy. Not For Distribution.


Selenium Webdriver

Now take the old version or any recommended version of Firefox to be


installed (Recommended old version: Firefox 33,Firefox 45 for
windows).

How to handle chrome driver issues ?


Eclipse Logs on test failures:
Starting ChromeDriver 2.20.353145
(343b531d31eeb933ec778dbcf7081628a1396067) on port 16538
Only local connections are allowed.
Exception in thread "main" org.openqa.selenium.WebDriverException:
unknown error: unhandled inspector error: {"code":-
32603,"message":"Cannot navigate to invalid URL"}
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.20.353145
(343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows
NT 6.3 x86_64) (WARNING: The server did not provide any stacktrace
information)
Command duration or timeout: 12 milliseconds
Build info: version: '3.0.0-beta2', revision: '2aa21c1', time: '2016-08-02
15:03:28 -0700'
System info: host: 'SweetHome', ip: '192.168.0.2', os.name: 'Windows
8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.chrome.ChromeDriver

Recommendation: Please make sure that the compatible and feasible


version of Chrome,Firefox or IE needs to be placed in Browser Drivers
folder and rerun the tests.

Problem Solving Section-Selenium WebDriver


Every test specialist go through a hard phase of fixing issues in
automation frameworks and investigation around test execution failures;
Fixing such complex issues need expertise on the test tool and problem
solving skills to overcome such project challenges; This section answers
to some of the latest challenges and questions in automation test scripts
using Selenium WebDriver.

How to fix a problem when driver throws Null Pointer exception in the
code?
Code Snippet:

165

Author Copy. Not For Distribution.


Narayanan Palani

Figure 122 VerifyPageTitle Code Sample

Error:

Figure 123 Error Screenshot

Solution:
Driver is not initialised in this script using driver.get(" ") command
hence null pointer exception is thrown during test execution. Driver has
to be initialised in row 15 to solve this issue.
Sample code (launch browser) to rectify this problem:

166

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 124 BasePage Script

Why there is an POIXML Exception displayed when test data handled


from Excel file?
Exception:

Figure 125 POIXMLException

Test Data used:

Figure 126 Object Repository in Excel File

167

Author Copy. Not For Distribution.


Narayanan Palani

Solution:
POIXML exception is caused due to formatting error while sending from
excel file to selenium framework. The best suggestion to overcome such
issues would be to convert the value to string using toString() method.

How to handle exception of chrome browser when firefox browser is


launched?
Exception Thrown at Run Time:

Figure 127 WebDriver Exception

Solution:
Check the driver and try to use Firefox version 46 or 33 to overcome the
exceptions; If chrome browser is renamed and placed in location which
is referred in script using line19, it is possible to get such exceptions
hence use the right browser for authentication.

What would be expected when Firefox exception 'Unable to connect to host'


occurred?

Figure 128 'Unable to connect to host' Exception during Test


Execution (within Output Console)

Configuration: Firefox 48.0.2 installed with Eclipse version 4.6.0;


Solution: This exception occurred due to incompatibility/higher version
of Firefox which is not compatible to Selenium WebDriver 2.43.o; So it
is suggested to downgrade the Firefox to 43 (anything less than 46) or
Firefox 33 which are compatible to Selenium WebDriver 2.o version.
Suggested versions: Selenium WebDriver 2.53.0 works well with
Firefox version 46.0 (So it is highly recommended to install this
version of firefox within the target machine when Selenium

168

Author Copy. Not For Distribution.


Selenium Webdriver

WebDriver 2.53 is referenced in build path of the Java based


Automation Framework)

How to execute TestNG based tests in right priority?


Code Snippet:

Figure 129 TestNG tests with Priority

When this test is executed with priority=1, following will be the results:
a Executed with result 4
Reason: TestNG identify the tests based on alphabetical order of the
classes and execute the first test of priority=1 and nothing else!
If all the priority are removed then, it executes the tests in the order of a,
b, c and d hence the results will be 4,2,3,1

What would be reason why the correct browser driver gives an exception?
Exception thrown as 'Unsupported Class Version Error':
Configuration
Target machine Time); : 64 bit (where the test is getting executed
during Run
Driver configured : 32 bit Chrome Driver;
Eclipse : Mars2 version;
Java : JDK 1.7

Problem:

169

Author Copy. Not For Distribution.


Narayanan Palani

Capital C is entered in the script in which Selenium is unable to invoke


the Chrome browser!.
Follow the script:

Figure 130 UnsupportedClassVersionError in Output Console

Solution:
Step1:
WebDriver.chrome.driver has to be updated in set property to avoid the
exception.
Step2:
Replace the existing 32 bit chrome browser driver to 64 bit chrome
browser driver since the target machine is 64 bit
Step3:
Downgrade(Uninstall) the chrome browser in target machine if it is
higher version then the browser driver and keep the right version of
chrome to install in the target machine (which should match the
automation framework chrome driver's version)

Why TestNG tests fail only in eclipse and works fine in command
prompt?
At times it is possible that the tests works fine from command prompt
but it may fail due to configuration due the classpath in eclipse with the
below error:

Figure 131 Error Description

170

Author Copy. Not For Distribution.


Selenium Webdriver

This failure on test configuration may throw the TestNGException:

Figure 132 TestNG Exception

Suggestions:
Class path may have been made different from setting path to read config
or excel sheets or input data files which result in such TestNG
Exceptions. It is advised to revise the class path and rerun the tests.

Selenium Test Automation Best Practices


Test Automation Frameworks increases the overall code base when
project moves towards multiple cycles and regression packs are loaded
with multiple scripts. In order to maintain the automation scripts, it is
always suggested to follow best practices. Readers are suggested to refer
the book 'Clean Code: A Handbook of Agile Software Craftsmanship by
Robert C. Martin' for better implementation of coding standards. This
section explains practices primarily on selenium based frameworks using
java as coding language

Naming Standards in Java based Frameworks


Data Type Suggested Prefix Examples
Global g gStrtype
Module-level m mIntID
Static s sintdob
Variable Passed by Reference r rIntID
Variable Passed by Values v vintAge
Local to the Function None strName
Boolean bin binStatus
Integer int intID

171

Author Copy. Not For Distribution.


Narayanan Palani

Long lng lngRef


Double dbl dblCount
Object obj objNext
String str strName
Single sng sngRow
Array arr arrProducts
User-Defined Type udt udtStock

Function Standards in Java based Frameworks


Every base java class of test scripts can be prefixed with 'SuiteBase' to
maintain similarity on the suite names for extending them across other
classes.

Selenium WebDriver and Ruby based Automation Framework


One of the latest selenium automation framework getting more attraction
in the recent years is based on Ruby scripting and it is expected to grow
similar to .Net based Selenium Frameworks in near future. In order to
script in Ruby, TestWise, RSpec, Selenium WebDriver are required to
develop this framework.
Writing Selenium based framework using Ruby need set of Gem
files to get created and plugged to the automation framework.

Comparison between Selenium frameworks:


Type of Java Based Net Based Ruby Based
Capabilities Selenium Selenium Selenium
Framework Framework Framework
BDD Cucumber Specflow/Specflo RSpec,RwebS
w+ pec
IDE Eclipse, IntelliJ Visual Studio TestWise
Test TestNG, JUnit, Visual Studio, TestWise,Com
Execution Ant, Maven etc NUnit etc mand Prompt
etc

TestWise is used as IDE(platform to write scripts for selenium)


within Ruby based framework where as Eclipse IDE or IntelliJ are used
as platforms to write scripts in Java based selenium frameworks; In case
of .Net framework, it is visual studio act as platform to write C#/C++
code for the .Net Selenium frameworks;

172

Author Copy. Not For Distribution.


Selenium Webdriver

Cucumber is used in Java based frameworks to implement BDD


based features and Rspec is used within Ruby based framework within
TestWise; Specflow and Specflow+ are used within Visual Studio for
.Net framework in this case.

Script Reference:
 https://github.com/narayananpalani/testautomation/tree/master/016C
andidateVerificationFormAutoTest
 Please download the complete project from above link using
Download Zip option and read the details further for better
understanding and clarity of the project design.

Install TestWise from the


website:http://testwisely.com/testwise/downloads
Once TestWise is installed, Open File->Create New Project->Give
Project Name

Example:

Figure 133 New Project Name

173

Author Copy. Not For Distribution.


Narayanan Palani

Once project is created already, create an ruby file within spec folder.
Example:

Figure 134 New File

Create the folder structure as below:

Figure 135 login_spec.rb file

Note: Only RSpec file (from spec folder) and test_helper.rb are
explained within this book as rest of the ruby gems can be accessible and
downloadable from GitHub and referred directly.

Capture the objects from the below webpage:


https://docs.google.com/forms/d/e/1FAIpQLScLxTQWgPTnbxTi3uLQN
PE2z4r8S_ZRcGTbfSU--WfGNDzQ0Q/viewform

174

Author Copy. Not For Distribution.


Selenium Webdriver

When the page is opened in firefox, right click on the first textbox(of full
name) and choose XPath Checker (Pre-requisite:Xpath Addon) and copy
the id which is available within the brackets:

Figure 136 Capturing XPath for the Object

Similarly right click on Email ID text box and choose Xpath Checker to
capture the id as entry_1000013 which need to be placed within the ruby
script of automation framework in testhelper file:

Figure 137 Capturing XPath for the Object

Right click on Contact text box and choose Xpath Checker to capture the
id as entry_1000014 which need to be placed within the ruby script of
automation framework in testhelper file:

175

Author Copy. Not For Distribution.


Narayanan Palani

Figure 138 Capturing Xpath for the Object

Follow the xpath identification steps for rest of the fields till submit
button and then feed the xpath details and write code in test_helper.rb as
below:

Figure 139 Updating XPath within the Scripts

Code Revision1: Writing the code mentioned above will lead to test
failure! The reason is on row92! Experience is a radio button which
needs to be clicked instead of sending the inputs of experience hence that
needs to be revised as:
driver.find_element(:id,'entry_1000000').send_keys(fullname)
driver.find_element(:id,'entry_1000013').send_keys(emailid)
driver.find_element(:id,'entry_1000014').send_keys(contactnumber)
driver.find_element(:id,'group_1000001_1').click
driver.find_element(:id,'entry_1000002').send_keys(sapexp)
driver.find_element(:id,'entry_1000003').send_keys(netweaverexp)
driver.find_element(:id,'entry_1000004').send_keys(kernelexp)
driver.find_element(:id,'entry_1000005').send_keys(currentcompany)
driver.find_element(:id,'ss-submit').click

176

Author Copy. Not For Distribution.


Selenium Webdriver

Code Revision2: At times in many machines, Submit button may not fit
to the browser screen hence user may need to press scroll down bar to
view submit button which is not scripted in code as generally it is not the
problem in all machines and applicable only to small screens.

How to handle such odd cases?


Drag event has to be scripted to perform scroll bar down and make sure
the broswer display submit button in every browser as TestWise can run
the same scripts in IE,Firefox and Chrome.

Code Revision3: After clicking on Submit button, it takes few minutes


to communicate(send request,save in database) through server and
receive the response but automation script never wait that many
milliseconds mostly.
In order to get the script waiting to validate the success message in
the next page, it is highly suggested to wait or sleep for few milliseconds
within Rspec file as below:
it "[1] Candidate can be verified" do
verify("Mark Harrison",
"mark@testlab.com","07878345445","6","2","1.5","2","ABCltd")
sleep 10
expect(page_text).to include("Your response has been recorded")
end

Update URL to test in test_helper and project settings:


Update the target URL in test_helper.rb as TXT_URL as follows:

Figure 140 Update the URL to test

Navigate to Tabs, Tools->Project Settings and update url within


Environments->Development:

177

Author Copy. Not For Distribution.


Narayanan Palani

Figure 141 Update Development in Environments

login_spec.rb:
This line refers to the test helper file to extend the script and get the
relevant ruby scripts:
load File.dirname(__FILE__) + '/../test_helper.rb'
Specification details:
describe "User Auth" do
include TestHelper
Prerequisite to the tests-run before the actual test1:
before(:all) do
@driver = $browser = Selenium::WebDriver.for(browser_type)
@driver.navigate.to(site_url)
sleep 10
end
Post completion of tests, following scripts are to be executed:
after(:all) do
@driver.quit unless debugging?
end

178

Author Copy. Not For Distribution.


Selenium Webdriver

First test within the ruby framework:


it "[1] Candidate can be verified" do
Test inputs are hardcoded in the script:
verify("Narayanan",
"narayanan@testlab.com","07878345445","6","2","1.5","2","ABCltd")
It is good to wait once the form is filled as it may take a few seconds to
see the response hence sleep code to wait for 10 seconds:
sleep 10
This message is to be verified in the response once the form is filled:
expect(page_text).to include("Your response has been recorded")
end
end

test_helper.rb:
Similar to Import in Java framework, 'require' is used in ruby based
scripting:
Rubygems required for scripting:
require 'rubygems'
Selenium required to execute the tests:
require 'selenium-WebDriver'
RSpec is required to script the behavior/specification of the tests:
require 'rspec'
Use utils in RWebSpec and better integration with TestWise:
require "#{File.dirname(__FILE__)}/rwebspec_utils.rb"
When running in TestWise, it will auto load TestWiseRuntimeSupport,
ignore otherwise:
if defined?(TestWiseRuntimeSupport)
::TestWise::Runtime.load_WebDriver_support # for selenium
WebDriver support
else
require "#{File.dirname(__FILE__)}/testwise_support.rb"
end
# this loads defined page objects under pages folder
require "#{File.dirname(__FILE__)}/pages/abstract_page.rb"
Dir["#{File.dirname(__FILE__)}/pages/*_page.rb"].each { |file| load file
}

The default base URL for running from command line or continuous
build process:

179

Author Copy. Not For Distribution.


Narayanan Palani

$TXT_URL =
"https://docs.google.com/forms/d/e/1FAIpQLScLxTQWgPTnbxTi3uLQ
NPE2z4r8S_ZRcGTbfSU--WfGNDzQ0Q/viewform"
# This is the helper for your tests, every test file will include all the
operation
# defined here.
module TestHelper
include RWebSpecUtils
if defined?(TestWiseRuntimeSupport) # TestWise 5
include TestWiseRuntimeSupport
else
include TestWiseSupport # TestWise 4
end
def browser_type
if $TESTWISE_BROWSER then
$TESTWISE_BROWSER.downcase.to_sym
elsif ENV["BROWSER"]
ENV["BROWSER"].downcase.to_sym
else
RUBY_PLATFORM =~ /mingw/ ? "ie".to_sym : "firefox".to_sym
end
end
alias the_browser browser_type
def site_url(default = $TXT_URL)
$TESTWISE_PROJECT_TXT_URL || ENV['TXT_URL'] || default
end
def driver
@driver
end
alias browser driver
def page_text
driver.find_element(:tag_name => "body").text
end
def visit(path)
driver.navigate.to(site_url + path)
end
Following section is the primary element within the Ruby Framework; It
has to be updated with respective xpath of the objects and get the inputs
through the parameters:

180

Author Copy. Not For Distribution.


Selenium Webdriver

def verify(fullname,
emailid,contactnumber,experience,sapexp,netweaverexp,kernelexp,c
urrentcompany)
driver.find_element(:id,'entry_1000000').send_keys(fullname)
driver.find_element(:id,'entry_1000013').send_keys(emailid)
driver.find_element(:id,'entry_1000014').send_keys(contactnumber)
driver.find_element(:id,'group_1000001_1').click
driver.find_element(:id,'entry_1000002').send_keys(sapexp)
driver.find_element(:id,'entry_1000003').send_keys(netweaverexp)
driver.find_element(:id,'entry_1000004').send_keys(kernelexp)
driver.find_element(:id,'entry_1000005').send_keys(currentcompany
)
sleep 10
driver.find_element(:id,'ss-submit').click
end
end

Note: verify is the function called within the RSpec file and sent the raw
inputs through that and received by test helper file. When this test is
executed, RSpec file talks to Test Helper and feed the test inputs to the
browser page and perform the actions.

Test Execution:
Open the project from TestWise by clicking
CandidateVerificationFormAutoTest.tpr and navigate to Spec folder.
Click on .rb file within spec folder and click on the Run Icon in TestWise
or Run->Run Test in Tabs and verity the test execution:

Figure 142 Run the Test

When the test is passed, it will be updated in Run Section:

Figure 143 Test Execution Status

181

Author Copy. Not For Distribution.


Narayanan Palani

Test Output section displays the list of tests and their duration of test run:

Figure 144 Test Output

Test Report section displays the overall test status with respect to the
specifications:

Figure 145 Test Results

JavaScript based Selenium Cucumber Automation Framework on


Linux
Most of the Selenium WebDriver books explain about theory or
framework with java/dot net possibilities; But only few blogs are actually
available about Linux based Selenium Implementation; It is very
important to know how an automation framework can be design in
operating systems other then Windows versions. This section describes
more on Java Script based Selenium Framework to work on Chrome
Browser and Linux platforms

Reference:
 https://github.com/Matt-B/cucumber-js-selenium-WebDriver-
example
 Where you can find this file in framework: cucumber-js-selenium-
WebDriver-example-master\cucumber-js-selenium-WebDriver-
example-master\features

182

Author Copy. Not For Distribution.


Selenium Webdriver

 File Name: google.feature


 Coding Style: Gherkin Programming

The below scripts are written by understanding the core concepts given
in the git project in reference section above. So download the project
from git and replace feature file and step definitions with the scripts
given in this section:

Figure 146 Feature File

Feature File:
Feature: Candidate Verification Form
As an internet user
In order to find out job in SAP
I want to be able to submit the candidate verification form

Scenario: Successful Submission of Candidate Information


When I Launch HR Candidate Verification Form
Then I should enter details to submit the Form

Step Definition File:

Figure 147 Step Definition File

'use strict';
var expect = require('chai').expect;
module.exports = function() {
this.World = require('../support/world.js').World;
this.When(/^I Launch HR Candidate Verification Form$/, function
(searchQuery) {
this.driver.get('https://docs.google.com/forms/d/e/1FAIpQLScLxTQWgP
TnbxTi3uLQNPE2z4r8S_ZRcGTbfSU--WfGNDzQ0Q/viewform');

183

Author Copy. Not For Distribution.


Narayanan Palani

});
this.Then(/^I should enter details to submit the Form$/, function () {
this.driver.findElement({ name: ' entry_1000000' })
.sendKeys("Albert Einstein");
this.driver.findElement({ name: ' entry_1000013' })
.sendKeys("albert@einstein.co.uk");
this.driver.findElement({ name: ' entry_1000014' })
.sendKeys("07867563478");
this.driver.findElement({ name: ''group_1000001_1' })
.click();
this.driver.findElement({ name: ' entry_1000002'})
.sendKeys("2");
this.driver.findElement({ name: ' entry_1000003'})
.sendKeys("1.5");
this.driver.findElement({ name: ' entry_1000004'})
.sendKeys("1");
this.driver.findElement({ name: ' entry_1000005'})
.sendKeys("1");
this.driver.findElement({ name: ' ss-submit'})
.click();
});
};

Explanation on the feature file:


Due the 'When' condition following page getting launched in Chrome
browser:

184

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 148 Web Page Designed to Test

'Then' condition sends the user inputs to the page and click on submit
button hence form is getting submitted.
Prerequisite for this project-Chrome Driver:
Chrome driver can be installed from
http://chromedriver.storage.googleapis.com/index.html
Once installed, add the reference to the 'Path' in Linux box as follows (if
the driver is placed in drivers folder within D drive),
export PATH=$PATH:~/D:/Drivers/chromedriver
Validate if it is working as expected (by entering chromedriver in your
terminal and validate the response like the below):
[naru@computer ~]$ chromedriver
Starting ChromeDriver (v2.11) on port 9515
Only local connections are allowed.
Press Ctrl+C to come out of the above message and navigate to the folder
where the script is placed by entering cd <path> command;
If the project folder is selenium – automation – framework - using
javascript, enter as:

185

Author Copy. Not For Distribution.


Narayanan Palani

cd selenium-automation-framework-using-javascript
Once navigated to the project folder,enter:
npm install
node_modules/grunt-cli/bin/grunt
The above lines to navigate to step definitions using gruntfile.js to run
the tests and produce results like the below:
[naru@computer selenium-automation-framework-using-javascript]$
grunt
Running "jshint:files" (jshint) task
>> 4 files lint free.
Running "exec:run_cucumber_tests" (exec) task
Feature: Candidate Verification Form
As an internet user
In order to find out job in SAP
I want to be able to submit the candidate verification form
Scenario: Successful Submission of Candidate Information#
features/google.feature:6
When I Launch HR Candidate Verification Form #
features/google.feature:7
Then I should enter details to submit the Form #
features/google.feature:8
1 scenario (1 passed)
2 steps (2 passed)
Done, without errors.

Selenium IDE Scripts to JMeter Scripts -Performance Testing


Techniques
Pre-Requisites to get Jmeter and Selenium IDE
Install JAVA:
Please kindly refer initial reference sections in this book chapter titled '
Download Selenium Projects from Github' to get JAVA installed on the
target machine.
Setup JAVA_HOME and PATH within the target machine

186

Author Copy. Not For Distribution.


Selenium Webdriver

Install Firefox:

Figure 149 Download Firefox

URL:
https://ftp.mozilla.org/pub/firefox/releases/33.0/win32/en-GB/
Once Firefox is installed, install Selenium IDE addin and restart firefox.*
Make sure you have right compatible firefox browser version installed.
*Note:This is described clearly in the first chapter.

Install JMeter:

Figure 150 Download JMeter

URL:
http://jmeter.apache.org/download_jmeter.cgi

How to Install Selenium IDE?


Install Firefox and click on Tools button and Add-ons button:

Figure 151 Add-ons of Firefox Browser


187

Author Copy. Not For Distribution.


Narayanan Palani

In the search box, search for Selenium IDE and download. Alternatively
navigate to http://www.seleniumhq.org/download/ and download from
the below link:

Figure 152 Downlaod any latest version of Selenium IDE

Once installed, please restart firefox to get an icon of Selenium IDE on


top right corner of Firefox. Click on logo of IDE on top right corner of
Firefox and view IDE along with browser.

Figure 153 Once Installed, Selenium IDE available as an Icon on top


right corner of the Firefox browser

Performance Testing Basics


Some Basics on Performance Testing is recommended before getting into
accessing performance
testing tools hence below section is provided to benefit readers on
performance testing basics.

Introduction to Performance Testing


Performance in terms of responsiveness and stability are measured using
various performance testing tools. Non functional testing (known as
NFT) is performed in most of the I.T Projects to analyze the scalability,
reliability and resource usage of the application under test (known as
AUT).
E.g: Testing Automated Teller Machine (ATM)machine functionality
when multi-users are accessing the application to withdraw cash.
188

Author Copy. Not For Distribution.


Selenium Webdriver

Basic Definition
Load test is the simplest form of performance test to understand the
scalability, reliability of the AUT under a specific expected load and this
load can be number of users on the application performing a specific
number of transactions within the set of duration.

Main Objectives
 To enhance the quick responsiveness of the AUT and better user
experience
 To improve the usability
 To make a comfortable end user journey
 To ensure that the AUT performs the number of
processes/transactions as per the key performance indicators
expected
 To provide better comparison results and metrics to understand
which system perform better
 To measure particular part of the system or workload which cause
the system performance badly

General Observation
System performance is mostly measured by Response Time Per User
Activity

What is Response Time?


Amount of time taken to process the particular user action.
E.g: Time taken to display homepage after logging into the application.

How does it difference from Functional Testing?


Functional Testing is performed to verify and validate the correctness of
the system process. Performance Testing is mostly used to verify the
overall performance and responsiveness of the AUT at high load and
stress conditions.

How to Launch JMeter?


Navigate to bin folder of Jmeter downloadable and click on jmeter.bat
file,

189

Author Copy. Not For Distribution.


Narayanan Palani

Figure 154 JMeter.bat File

After a brief wait, Jmeter launches a command prompt for its script to
run in background and launches the GUI of JMeter like the below:

Figure 155 Test Plan of JMeter

Right click on the Workbench (Note: not on the TestPlan),Select


Add,Non-Test Elements,HTTP(s) Test Script Recorder (where as old
JMeter have the same functionality called 'HTTP Proxy Server'):

Figure 156 Add HTTP(s) Test Script Recorder


in Workbench of JMeter
190

Author Copy. Not For Distribution.


Selenium Webdriver

It will be added like the below:

Figure 157 HTTP(s) Test Script Recorder in Workbench of JMeter

Enter Name as 'Recorder', Port 8080, Target Controller as


Workbench>HTTP(s) Test Script Recorder and Grouping as 'Add
Separators between groups':
Note: Groups are the set of http requests which are related to one another
from the same page in most of the tests.

Figure 158 Name:Recorder

Click on 'Start' on the HTTP(s) Test Script Recorder:

Figure 159 Click Start

191

Author Copy. Not For Distribution.


Narayanan Palani

Note:

Figure 160 Error Notified when Port number already in use

If there is an error message that 8080 is already used, it means Java


Virtual Machine is already using it and try using 8182 instead of 8080
like the below[Basically both the places should show same port
number.Example 8080 should be displayed in Selenium IDE as well as
JMeter]:

Figure 161 Update Port Number

192

Author Copy. Not For Distribution.


Selenium Webdriver

'Allow access ' in case asked by firewall settings:

Figure 162 Firewall Security Alert-Click on Allow Acces for


Java to run the Tests

Click OK for the below message box:

Figure 163 Click OK button for the Certificate

Navigate to Firefox, click on the Tools menu item and Options:

Figure 164 Tools and Options

193

Author Copy. Not For Distribution.


Narayanan Palani

Click on 'Advanced' and 'Network' within Advanced like the below:

Figure 165 Click Advanced in Options and Choose Network

194

Author Copy. Not For Distribution.


Selenium Webdriver

Click on Setttings in the Network tab of Advanced, and select Manual


Proxy Configuration and enter localhost as http proxy and 8182 as port:

Figure 166 Manual Proxy Configuration

Click OK on the settings of Firefox and then launch Selenium IDE*:


Open one of the existing tests created in Selenium IDE and run them
using 'Playback' option,

195

Author Copy. Not For Distribution.


Narayanan Palani

Figure 167 Selenium IDE and JMeter

*Selenium IDE has to be installed in Firefox to use it in this scripting.


Please watch the section 'Prerequisites' to know how to install Selenium
IDE for Firefox browser

Once clicked on Run in Selenium IDE, wait until the tests get completed:

Figure 168 Selenium IDE Scripts

196

Author Copy. Not For Distribution.


Selenium Webdriver

Navigate to JMeter which is currently started and recording the Selenium


IDE scripts in the background. Since scripts are executed in Selenium
IDE, navigate to JMeter and STOP therecord:

Figure 169 Recorder

Expand the Recorder in JMeter and identify those new tests created using
Selenium IDE:

Figure 170 Recorder (of JMETER) updated with scripts when


Selenium IDE scripts are executed from Selenium IDE

197

Author Copy. Not For Distribution.


Narayanan Palani

Expand those each element validate those steps which are recorded using
Selenium IDE into JMeter:

Figure 171 Expand JMeter Recorder

Now Save the test plan of JMeter using, 'File' menu, select 'Save Test
Plan As':

Figure 172 Save Test Plan of JMeter

Now please navigate to Firefox, Tools, Options, Advanced, Network,


Settings and set to 'No Proxy':

198

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 173 Change the Proxy back to 'No Proxy'


once the Recording is completed

Now the scripts are recorded in JMeter which can be used further to
run the Non Functional/Performance Tests for the same project hence
Selenium scripts are reused in JMeter for Performance Tests with almost
same set of steps followed in Selenium while creating those steps!

Reference:
 Ellie Skobel. (2016, September 10), Selenium Minutes [Web log
post]. Retrieved from http://seleniumminutes.com/

199

Author Copy. Not For Distribution.


Narayanan Palani

Advanced Selenium IDE


When there are multiple test sets created with Selenium IDE, there are
real challenges to maintain them and testers are limited with few
selenium features. But it is possible to use best plug-ins to support
selenium and get new functionalities extended such as capture
screenshots, test reports etc.

Steps to Install Additional Plugins


 Project Location:
testautomation\003SeleniumIDE-TestProject\SELENIUMWEBPAGE-
AUTOMATION\Shivani
GITHUB URL:
https://github.com/narayananpalani/testautomation/blob/master/003Selen
iumIDE-TestProject/SELENIUMWEBPAGE-
AUTOMATION/Shivani/selenium_projects6.html

Refer the html file 'selenium_projects6.html' and try to open the file in a
browser such as firefox and following scripts will be viewed in tabular
column:
selenium_projects6
open /projects/
clickAndWait link=Selenium Projects
clickAndWait link=Download
clickAndWait link=Documentation
verifyText css=a.reference.internal Note to the Reader - Docs
Being Revised for Selenium
2.0!
verifyElementPresent link=Introduction
verifyText link=Test Automation for Test Automation for Web
Web Applications Applications
verifyText link=exact:To Automate exact:To Automate or Not to
or Not to Automate? Automate?
assertText link=Introducing Introducing Selenium
Selenium
verifyElementPresent link=Brief History of The
Selenium Project
assertElementPresent link=Selenium‘s Tool
Suite
verifyText link=Choosing Your Choosing Your Selenium Tool
Selenium Tool
assertText link=Supported Browsers Supported Browsers and
and Platforms Platforms
verifyText link=Flexibility and Flexibility and Extensibility

200

Author Copy. Not For Distribution.


Selenium Webdriver

Extensibility
assertElementPresent link=exact:What‘s in this
Book?
verifyText link=The Documentation The Documentation Team–
Team–Authors Past and Authors Past and Present
Present
assertElementPresent link=Selenium-IDE
verifyText xpath=(//a[contains(text(),' Introduction
Introduction')])[2]
verifyTitle Selenium Documentation -
Selenium Documentation
assertElementPresent link=Installing the IDE
verifyElementPresent link=Installing the IDE
assertElementPresent link=Opening the IDE
verifyText link=IDE Features IDE Features
verifyElementPresent link=Building Test Cases
assertText link=Using Base URL to Using Base URL to Run Test
Run Test Cases in Cases in Different Domains
Different Domains
verifyText link=Using Base URL to Using Base URL to Run Test
Run Test Cases in Cases in Different Domains
Different Domains
assertElementPresent link=Selenium Commands
– ―Selenese‖
assertElementPresent link=Script Syntax
verifyText link=Test Suites Test Suites
assertText link=Commonly Used Commonly Used Selenium
Selenium Commands Commands
verifyText link=Verifying Page Verifying Page Elements
Elements
assertText link=exact:Assertion or exact:Assertion or
Verification? Verification?
verifyElementPresent link=Locating Elements
verifyText link=Matching Text Matching Text Patterns
Patterns
assertElementPresent link=The ―AndWait‖
Commands
verifyElementPresent link=The waitFor
Commands in AJAX
applications
verifyText link=Sequence of Sequence of Evaluation and
Evaluation and Flow Flow Control
Control
assertElementPresent link=Store Commands and
Selenium Variables

201

Author Copy. Not For Distribution.


Narayanan Palani

verifyText link=Store Commands and Store Commands and Selenium


Selenium Variables Variables
assertText link=JavaScript and JavaScript and Selenese
Selenese Parameters Parameters
verifyText link=echo - The Selenese echo - The Selenese Print
Print Command Command
assertText link=Alerts, Popups, and Alerts, Popups, and Multiple
Multiple Windows Windows
verifyText link=Debugging Debugging
assertText link=Writing a Test Suite Writing a Test Suite
verifyText link=User Extensions User Extensions
assertText link=Format Format
verifyText link=Executing Selenium- Executing Selenium-IDE Tests
IDE Tests on Different on Different Browsers
Browsers
assertText link=Troubleshooting Troubleshooting
verifyTitle Selenium Documentation
— Selenium
Documentation
verifyElementPresent link=Introducing
WebDriver
assertText link=exact:How Does exact:How Does WebDriver
WebDriver ‗Drive‘ the ‗Drive‘ the Browser Compared
Browser Compared to to Selenium-RC?
Selenium-RC?
verifyText link=WebDriver and the WebDriver and the Selenium-
Selenium-Server Server
assertElementPresent link=Setting Up a
Selenium-WebDriver
Project
verifyText link=Migrating from Migrating from Selenium 1.0
Selenium 1.0
assertElementPresent link=Introducing the
Selenium-WebDriver API
by Example
verifyElementPresent link=Selenium-WebDriver
API Commands and
Operations
assertElementPresent link=Driver Specifics and
Tradeoffs
verifyText link=Selenium- Selenium-WebDriver‘s Drivers
WebDriver‘s Drivers
assertText link=Alternative Back- Alternative Back-Ends: Mixing
Ends: Mixing WebDriver WebDriver and RC
and RC Technologies Technologies
verifyText link=Running Standalone Running Standalone Selenium

202

Author Copy. Not For Distribution.


Selenium Webdriver

Selenium Server for use Server for use with


with RemoteDrivers RemoteDrivers
assertText link=Additional Resources Additional Resources
verifyText link=Next Steps Next Steps
verifyTitle Selenium Documentation
— Selenium
Documentation
verifyText link=Explicit and Implicit Explicit and Implicit Waits
Waits
assertElementPresent link=RemoteWebDriver
verifyText link=AdvancedUserIntera AdvancedUserInteractions
ctions
assertText link=Browser Startup Browser Startup Manipulation
Manipulation
verifyText link=HTML5 HTML5
assertText link=Parallelizing Your Parallelizing Your Test Runs
Test Runs
verifyTitle Selenium Documentation
— Selenium
Documentation
verifyElementPresent xpath=(//a[contains(text(),'
Introduction')])[3]
assertText link=How Selenium RC How Selenium RC Works
Works
verifyText link=Installation Installation
assertText link=From Selenese to a From Selenese to a Program
Program
verifyText link=Programming Your Programming Your Test
Test
assertText link=Learning the API Learning the API
verifyText link=Reporting Results Reporting Results
assertText link=Adding Some Spice Adding Some Spice to Your
to Your Tests Tests
assertText link=Server Options Server Options
verifyText link=Specifying the Path Specifying the Path to a
to a Specific Browser Specific Browser
assertText link=Selenium RC Selenium RC Architecture
Architecture
verifyText link=Handling HTTPS Handling HTTPS and Security
and Security Popups Popups
assertText link=Supporting Supporting Additional
Additional Browsers and Browsers and Browser
Browser Configurations Configurations
assertText link=Troubleshooting Troubleshooting Common
Common Problems Problems

203

Author Copy. Not For Distribution.


Narayanan Palani

assertText link=Test Design Test Design Considerations


Considerations
verifyText link=Introducing Test Introducing Test Design
Design
assertText link=Types of Tests Types of Tests
assertText link=Validating Results Validating Results
verifyText link=Location Strategies Location Strategies
assertText link=Wrapping Selenium Wrapping Selenium Calls
Calls
assertText link=UI Mapping UI Mapping
verifyText link=Page Object Design Page Object Design Pattern
Pattern
verifyText link=Data Driven Testing Data Driven Testing
assertElementPresent link=Database Validation
verifyTitle Selenium Documentation
— Selenium
Documentation
verifyText link=Quick Start Quick Start
assertText link=exact:What is exact:What is Selenium-Grid?
Selenium-Grid?
assertElementPresent link=When to Use It
verifyText link=Selenium-Grid 2.0 Selenium-Grid 2.0
verifyText link=How Selenium-Grid How Selenium-Grid Works–
Works–With a Hub and With a Hub and Nodes
Nodes
verifyTitle Selenium Documentation
— Selenium
Documentation
verifyText link=Configuring Configuring Selenium-Grid
Selenium-Grid
assertText link=Hub Configuration Hub Configuration
verifyText link=Node Configuration Node Configuration
verifyText link=Timing Parameters Timing Parameters
verifyText link=Customizing the Grid Customizing the Grid
assertText link=Getting Command- Getting Command-Line Help
Line Help
assertText link=Common Errors Common Errors
verifyTitle Selenium Documentation
— Selenium
Documentation
verifyText link=Actions Actions
verifyText link=Accessors/Assertions Accessors/Assertions
assertText link=Locator Strategies Locator Strategies
verifyElementPresent link=Using User-
Extensions With

204

Author Copy. Not For Distribution.


Selenium Webdriver

Selenium-IDE
assertElementPresent link=Using User-
Extensions With Selenium
RC
verifyElementPresent link=.NET client driver
configuration
assertText link=Importing Sel2.0 Importing Sel2.0 Project into
Project into Eclipse using Eclipse using Maven
Maven
verifyText link=Importing Sel2.0 Importing Sel2.0 Project into
Project into IntelliJ Using IntelliJ Using Maven
Maven
assertText link=Migrating From Migrating From Selenium RC
Selenium RC to Selenium to Selenium WebDriver
WebDriver
verifyText link=How to Migrate to How to Migrate to Selenium
Selenium WebDriver WebDriver
assertText link=Why Migrate to Why Migrate to WebDriver
WebDriver
verifyText link=Before Starting Before Starting
assertText link=Getting Started Getting Started
verifyElementPresent xpath=(//a[contains(text(),'
Next Steps')])[2]
assertText link=Common Problems Common Problems
verifyText css=#mainContent > Selenium Documentation
div.related > ul > li > a
assertText css=#mainContent > next
div.related > ul > li.right >
a[title="Note to the
Reader - Docs Being
Revised for Selenium
2.0!"]
verifyElementPresent id=footerLogo
selectWindow null
verifyElementPresent link=Selenium
Documentation
assertText link=next next
verifyText link=Note to the Reader - Note to the Reader - Docs
Docs Being Revised for Being Revised for Selenium
Selenium 2.0! 2.0!
assertText css=em Docs Being Revised for
Selenium 2.0
verifyElementPresent name=submit
verifyText name=submit
assertElementPresent css=a > img
assertValue css=li > java

205

Author Copy. Not For Distribution.


Narayanan Palani

input[type="image"]
verifyValue //input[@value='csharp'] csharp
assertText //input[@value='python']
verifyText //input[@value='ruby']
assertValue //input[@value='php'] php
verifyValue //input[@value='perl'] perl
assertValue //input[@value='javascript javascript
']

Follow the steps below:


 Open this script using Selenium IDE (Steps: Launch Firefox, Goto
Addins-->Install Selenium IDE,Once Installed click on
'File>Open>')
 Launch the url given below and install ScreenShotOnFail:
https://addons.mozilla.org/en-US/firefox/addon/screenshot-on-fail-
selenium/

Figure 174 ScreenShot on Fail Add-on for Selenium IDE

Note: Restart Firefox after installing this plug-in.

 Launch the url given below and install PageCoverage:


https://addons.mozilla.org/en-US/firefox/addon/page-coverage-
selenium-ide/

206

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 175 Page Coverage Add-on for Selenium IDE

Note: Restart Firefox after installing this plug-in.

Once both the tools are installed, they will appear as small icons in
Selenium IDE. In order to get these Plugins worked for a test case, they
have to be clicked as below:

Click on Page Coverage Icon (not on the down arrow):

Figure 176Page Coverage Icon

Click on ScreenShotOnFail (not on the down arrow):

Figure 177 ScreenShotOnFail Icon

207

Author Copy. Not For Distribution.


Narayanan Palani

Once both the tools are clicked, run the test by click on Run button and
see the Test Results.If all steps are passed, edit any of the commands
with empty values and rerun to see atleast one failure in order to validate
the failure reports which are captured by these two tools.
Example: Perl id has been updated incorrectly as Per in selenium IDE
selenese script and then test run as below to see 1 error:

Figure 178 Selenium IDE with two add-ons

Steps to view Page Coverage using PageCoverage Plugin


Now click on Page Coverage Icon's dropdown and choose 'View Page
Coverage' option:

208

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 179 View Page Coverage

This action of clicking on View Test Coverage would have opened a file
directory within Firefox as below:

Figure 180 Page Coverage Report

This file contains the error report with the page where the object has
been failed to identify as per the object id entered.

209

Author Copy. Not For Distribution.


Narayanan Palani

Steps to view Screenshots for the Test Failures using ScreenShotOnFail


Click on ScreenShotOnFail's dropdown and select 'View Failure Report'
option:

Figure 181 View Failure Report

This action of clicking on View Failure Report would have opened a file
directory within Firefox as below:

Figure 182 Error Report

This file contains the failure screenshot report with the page where the
object has been failed to identify as per the object id entered.

Log Toolbar within Selenium IDE:

210

Author Copy. Not For Distribution.


Selenium Webdriver

When there are multiple test steps involved in tests and test execution
shows number of issues in logs, it is extremely difficult to go though the
table structure and understand what are the actual issues. In order to
simplify this search, Log Toolbar placed bottom of Selenium IDE to
enable testers to perform 'Find' option on the test Logs.
Install LogToolbar from following URL:
https://addons.mozilla.org/en-US/firefox/addon/log-search-bar-selenium-
ide/

Figure 183 Log Search Bar Add-on for Selenium IDE


Note: Restart Firefox after installing this plug-in.

Open selenium IDE to run the test using Run button and observe the list
of logs in Log Panel (bottom). Search for /Projects in LogSearchBar
plugin and it finds the relevant search query for testers as below:

211

Author Copy. Not For Distribution.


Narayanan Palani

Figure 184 Test Execution Status in Selenium IDE

Reference:
 AMAL BOSE. (2016, September 12), 8 Selenium IDE Plugins you
Should be Aware OfRetrieved from http://axatrikx.com/selenium-
ide-plugins/
 LogToolBar,ScreenShotOnFail,PageCoverage Plug-ins are designed
by Samit Badle
 Selenium IDE is designed by Jason Huggins, Adam Goucher, Shinya
Kasatani, Dave Hunt, Samit Badle
 Selenium IDE Plugins section from
http://www.seleniumhq.org/download/ can be referred for multiple
useful Plugins to use as part of Selenium IDE tests

212

Author Copy. Not For Distribution.


Selenium Webdriver

Automate CRM Applications using Selenium WebDriver Page


Object Model (POM)
Salesforce is one of the top leading CRM application in IT industry and
automating the test cases for Salesforce modules (known as SFDC-
SalesForceDotCom) is niche domain to get jobs in test automation with
considerable amount of pay in recent years. In this chapter, Salesforce
Trailhead's Login Page has been automated to display quickest
automation framework solution for CRM Test Automation!

Programming Language : Java Programming


Platform : Eclipse IDE
Tools Used: Selenium WebDriver (Scripting), Selenium IDE (only of
object capturing techniques), Eclipse
Trailheadxxiii is Salesforce's learning portal and 'Learn CRM Essentials'
sectionxxiv is very useful for anyone to understand how customer
information and sales information are configured and stored in CRM
application. Register yourself in Learn CRM Essentials with valid user id
and password; Once email acknowledgement has been completed, it is
possible to login to learning portal and learn important modules such as
contacts, contracts etc.

Figure 185 Trailhead Salesforce Page

Once registration has been successful, launch the salesforce trailhead


page to login using user id and password and parallel to login, record the
events in Selenium IDE:

213

Author Copy. Not For Distribution.


Narayanan Palani

Figure 186 Objects of Login Page displayed in


Selenium IDE Target Column

Note: Firefox browser should be used to install and launch Selennium


IDE. Basics of Selenium IDE is explained in Part 1.

Alternatively, right click on each object and select inspect element to


view their object id to automate the page.
If Selenium IDE is opened in the background, right click on the object to
view available commands as below:

Figure 187 Show All Available Commands (Option visible only when
Selenium IDE opened in background)

Steps to automate the login page


Fresh project has been created with brand new scripting steps to learn
Page Object Model (POM) in this section hence first set of scripts are
non-POM to explain how to script at first level and then two types of
POM techniques are explained.
Pre-requisites:

214

Author Copy. Not For Distribution.


Selenium Webdriver

 Download and Install Java


 Configure Java Home and Path
 Download and Install Eclipse IDE
 Download Selenium WebDriver files from seleniumhq.org
 Download Browser Driver for Chrome Browser

Launch Eclipse IDE and click on File-->New-->Java Project to give


project name as SalesforceTestAutomation:

Figure 188 Create New Java Project

215

Author Copy. Not For Distribution.


Narayanan Palani

Enter the project name and click on Next Button:

Figure 189 Java Project Name

216

Author Copy. Not For Distribution.


Selenium Webdriver

Click on Finish button:

Figure 190 Click on Finish Button

217

Author Copy. Not For Distribution.


Narayanan Palani

Expand the project in Package Explorer and view the empty project as
follows:

Figure 191 Verify JRE System Library


(displayed when Java installed)

Note: If JRE System Library is empty, java home and path setup must be
incorrect. Please refer initial chapters to set Java installation and
Home/Path setup
If Package Explorer is not visible, press Alt+Shift+Q, P to open or
navigate to Window-->Show View-->Package Explorer to open:

218

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 192 Package Explorer View

Alternatively watch online video ' Learn how to open Package explorer
tray in any Eclipse version'xxv
Next step is to add necessary JAR files to the project in order to
reference libraries related to our tests.Download latest selenium
WebDriver JAR files from seleniumhq.org and save them in a folder
called JARFiles within the project folder and then follow the steps below
to include all those downloaded jar files to the build path.
For example,
Navigate to http://www.seleniumhq.org/download/ and go to the section
'Selenium Client & WebDriver Language Bindings' and click on
download on the row where Java referened.
Extract the zip file when downloaded,use all the jar files referenced
below to add as external jars:

Figure 193 Jar files from Selenium Installable

219

Author Copy. Not For Distribution.


Narayanan Palani

Figure 194 Jar files from Selenium Installable

Note: All these jar files are to be included, not just one jar file displayed
in section1.

Navigate to Configure Build Path:

220

Author Copy. Not For Distribution.


Selenium Webdriver

Click on Add External Jars:

Figure 195 Libraries tab within Configure Build Path

Add relevant JAR files (refer all the jar files from section 1 and 2 and
include all of the here) which will be listed in the Project in Package
Explorer under the section 'Referenced Libraries' once added:

Once jar files are included, the next step is to write initial set of test
scripts to execute the test cases; In order to write tests, it is recommended
to create a package inside the src folder of project and create java file
within the package created (Project-src-package-java file).

221

Author Copy. Not For Distribution.


Narayanan Palani

Right click on src to create a new package as salesforcepack:

Figure 196 Create Package

Once package is created, create a Java class as follows:

Figure 197 Create Java Class File

Give class name as Contacts_Salesforce_TestCase1 and click on Finish:

222

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 198 Name of the Java Class File

Once class has been created, it displays an empty class file


'Contacts_Salesforce_TestCase1.java' like the below:

Figure 199 Class File with No Scripts in Early Stage

223

Author Copy. Not For Distribution.


Narayanan Palani

Create a new Folder from Project Level and name it as a


BrowserDrivers:

Figure 200 Create Folder

Download and Paste the latest Chrome Browser Driver under this folder:
Note: https://sites.google.com/a/chromium.org/chromedriver/downloads
is used to download the chrome driver. Choose right driver based on
windows or operating system specification. If win32 chrome driver is
downloaded and used for windows 64 bit operating system, it may lead
to exception and failures hence download right driver for the test

Figure 201 Browser Drivers

Navigate to class file ' Contacts_Salesforce_TestCase1.java':

Figure 202 Code Sample

Write these three lines of code at the section 1:


import org.openqa.selenium.By;

224

Author Copy. Not For Distribution.


Selenium Webdriver

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

Figure 203 Import Details

Overall code at the moment:


package salesforcepack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Contacts_Salesforce_TestCase1 {
}
Initiate the WebDriver with the code below at section2:
static WebDriver driver;

Figure 204 Code Sample

Write the below code at section3:


public static void main(String[] args){
}

225

Author Copy. Not For Distribution.


Narayanan Palani

Figure 205 Code Sample

Overall code at the moment:


package salesforcepack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Contacts_Salesforce_TestCase1 {
static WebDriver driver;
public static void main(String[] args){
}
}

Enter the lines of code below in section4:


System.setProperty("WebDriver.chrome.driver","E://AutomationProject/
/Training//SalesforceTestAutomation//BrowserDrivers//chromedriver.ex
e");

Figure 206 Code Sample


226

Author Copy. Not For Distribution.


Selenium Webdriver

Note: The path has to updated for every project and // to be used for
every folder level.

Enter the below line of code in section5:


driver = new ChromeDriver();

Figure 207 Code Sample

Now the driver instance has been created with the help of code
above.The next step is to launch the browser to get particular web page
such as https://login.salesforce.com.
Enter the line of code below at section6:
driver.get("https://login.salesforce.com");

Figure 208 Code Sample

Now the scripts are written to launch the browser and open particular
web page. Next step is to enter values to user name and password fields
and then click on Login button.
Capture the object ids of user name by right click on username textbox
and choose Inspect Element:

227

Author Copy. Not For Distribution.


Narayanan Palani

Figure 209 XPath of Username field

id='username' is identified by right clicking on user name hence the


xpath identification for this object (textbox) is username.
Capture the object ids of password by right click on username textbox
and choose Inspect Element:

Figure 210 XPath of Password field

228

Author Copy. Not For Distribution.


Selenium Webdriver

id='password' is identified by right clicking on password text box hence


the xpath identification for this object (textbox) is password.

Figure 211 XPath of Login Button


id='Login' is identified by right clicking on Login button hence the xpath
identification for this object (textbox) is Login.

Enter following line of codes in section 7 to fill the user inputs for user
name,password and click on Login button:
driver.findElement(By.xpath("//*[@id='username']")).sendKeys("Naraya
nanP@Raghava.co.uk");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Hello
World");
driver.findElement(By.xpath("//*[@id='Login']")).click();

Figure 212 Code Sample

229

Author Copy. Not For Distribution.


Narayanan Palani

Enter script to quit the browser once the test has been completed at
section8:
driver.quit();

Figure 213 Code Sample

Code snippet of this test:


package salesforcepack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Contacts_Salesforce_TestCase1 {
static WebDriver driver;
public static void main(String[] args){
System.setProperty("WebDriver.chrome.driver","E://AutomationProject/
/Training//SalesforceTestAutomation//BrowserDrivers//chromedriver.ex
e");
driver = new ChromeDriver();
driver.get("https://login.salesforce.com");
driver.findElement(By.xpath("//*[@id='username']")).sendKeys("Naraya
nanP@Raghava.co.uk");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Hello
World");
driver.findElement(By.xpath("//*[@id='Login']")).click();
driver.quit();
}
}

Click on Run button or alternatively right click on


Contacts_Salesforce_TestCase1.java and select Run As-->Java
Application to run this test:

230

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 214 Run as Java Application

While executing the test, observe the log outputs from console section:

Figure 215 Console Output

Introduction of Page Object Model


Creating Object Repositories is a best practice in automation frameworks
where as creating such Object Repositories for every web UI elements is
commonly known as Page Object Model (POM). Need of such POM
design is increased in the testing projects due to complexities across
framework maintenance. When page object properties such as id or xpath
are changed during life cycle of the product, it is flexible to get them
amended in automation framework when it is designed using POM. Else
if the framework designed without object repositories, rework and
maintenance time is very high to get the build ready for test execution.
Example: object id of user name field has been changed during spring 8
of agile project. If the framework designed without POM, tester has to
amend 300+ line of codes with latest object id where as the framework
with POM design need just a one line change to edit object property in
page object factory!

Advantages of POM based Automation Framework with examples


Every page has been referenced to a java class file within Object
Repository and used in test scripts and every page object property such
as xpath or id has been updated in an interface as members and called to
the tests in each java class file.
Example:
Object of UserName within Object Repository:
public void setSFUserName(String strUserName){
driver.findElement(txt_sfusername).sendKeys(strUserName);
}

Each functionality of respective objects are also designed within object


repository as a Functional Encapsulation Mechanism hence test has been
simplified.

231

Author Copy. Not For Distribution.


Narayanan Palani

Example:
Functional Encapsulation by sending User Input to UserName TextBox
within Object Repository:
public void setSFUserName(String strUserName){
driver.findElement(txt_sfusername).sendKeys(strUserName);
}

This line has been called in test case (class file) as the below:
objSFLogin = new LoginPageObjects();
objSFLogin.setSFUserName("NarayananP@Raghava.co.uk");
If there are plans to replace the automation engine from selenium
WebDriver to any other licensed automation tools, it can be considered
to automate using POM as the rework to assemble callable functions are
easy and feasible comparing to rebuild the whole automation framework.

Disadvantages of POM based Automation Framework with examples


If a normal automation framework takes (approx.) thirty five daysof
development time, POM design takes at least (approx.) ninety days to
develop the same set of framework components with complete page
object factory hence it is not a right solution for short term and
medium term projects and applicable as a best approach only for long
term projects.

Training fresher candidates with automation framework using page


object model is extremely time consuming and difficult.
If there are plans to switch programming languages when migrating
from one type of automation framework to other framework using
different tool, it is useless effort to build POM design.
If there are BDD (Behavior Driven Development) implementation to the
project to convert from Data Driven Framework (using excel files) to
Keyword Driven Framework (using Cucumber) lead to reconstruct the
entire functional encapsulation model which is more complex and
creating new automation framework takes lesser time rather than
reconstructing the whole Data Driven Framework.
Example:
Data Driven Framework constructed to get the user input from
parameters:
public void setSFUserName(String strUserName){
driver.findElement(txt_sfusername).sendKeys(strUserName);
}

232

Author Copy. Not For Distribution.


Selenium Webdriver

If decided to upgrade/migrate to BDD model, then it has to be


reconstructed within step definition file as the below:
@Given("Enter User Name in SF Website as '(.+)'")
public void addNewBook(final String strUserName,) {
driver.findElement(txt_sfusername).sendKeys(strUserName);
}

How to construct a Simple Page Object Model?


It is advised to get an object repository/page object factory constructed
within a package of java project.
Create a package from Project-->New-->Package as pageobjects

Figure 216 Create Package

Create a java file within the package called LoginPageObjects.java to


write the object repository elements:

233

Author Copy. Not For Distribution.


Narayanan Palani

Figure 217 Create Package and click Finish Button

234

Author Copy. Not For Distribution.


Selenium Webdriver

Once the java file has been created, it looks like the below:

Figure 218 Code Sample

Enter the line of code below to the section1 and watch yellow bulb
highlighted in left side(which says that the line of code is not used
anywhere at the moment):
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

Figure 219 Code Sample

Enter the line of code below to the section2:


By txt_sfusername = By.id("username");
By txt_sfpwd = By.id("password");
By btn_sflogin= By.id("Login");

Figure 220 Code Sample

235

Author Copy. Not For Distribution.


Narayanan Palani

Overall code status at the moment:


package pageobjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPageObjects {
WebDriver driver;
By txt_sfusername = By.id("username");
By txt_sfpwd = By.id("password");
By btn_sflogin= By.id("Login");
}

Figure 221 Code Sample

Enter the line of code below to the next section to enter value in
username textbox:
public void setSFUserName(String strUserName){
driver.findElement(txt_sfusername).sendKeys(strUserName);
}

Figure 222 Code Sample

Enter the line of code below to the next section to enter value in
password textbox:
public void setSFPassword(String strPassword){

236

Author Copy. Not For Distribution.


Selenium Webdriver

driver.findElement(txt_sfusername).sendKeys(strPassword);
}

Figure 223 Code Sample

Enter the line of code below to the next section to click on login button:
public void setSFLogin(){
driver.findElement(btn_sflogin).click();
}

237

Author Copy. Not For Distribution.


Narayanan Palani

Figure 224 Code Sample

Overall code status at the moment:


package pageobjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPageObjects {
WebDriver driver;
By txt_sfusername = By.id("username");
By txt_sfpwd = By.id("password");
By btn_sflogin= By.id("Login");
public void setSFUserName(String strUserName){
driver.findElement(txt_sfusername).sendKeys(strUserName);
}
public void setSFPassword(String strPassword){
driver.findElement(txt_sfusername).sendKeys(strPassword);
}
public void setSFLogin(){

238

Author Copy. Not For Distribution.


Selenium Webdriver

driver.findElement(btn_sflogin).click();
}
}

Introduce below line of code within the object repository to create


instance of driver:

Figure 225 Code Sample

Navigate to test scripts location (Contacts_Salesforce_TestCase1.java)


and enter the line of code below to the section1:
import pageobjects.LoginPageObjects;

Figure 226 Code Sample

239

Author Copy. Not For Distribution.


Narayanan Palani

Now remove the code written without POM design:

Figure 227 Code Sample

Replace with POM code:


LoginPageObjects objSFLogin;

Figure 228 Code Sample

Introduce below line of code to send user inputs to username field within
POM design based framework:
objSFLogin = new LoginPageObjects();
objSFLogin.setSFUserName("NarayananP@Raghava.co.uk");

240

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 229 Code Sample

Below line of code inserted to enter password within the page using
POM design:
objSFLogin.setSFPassword("HelloWorld");

Figure 230 Code Sample

241

Author Copy. Not For Distribution.


Narayanan Palani

Enter below line of code to click on Login button:

Figure 231 Code Sample

242

Author Copy. Not For Distribution.


Selenium Webdriver

Page Object Model-A simple alternative method


Create a Package called pomfunctions:

Figure 232 Create Java Package

243

Author Copy. Not For Distribution.


Narayanan Palani

Click on Finish button:

Figure 233 Create New Java Class

Enter below line of code in section1:


import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

244

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 234 Code Sample

Find the code to encapsulate username input function within the object
repository hence this function has been called within test script for every
need of username input:

Enter below line of code in section2:


private static WebElement element = null;
public static WebElement txt_sfusername(WebDriver driver){
element = driver.findElement(By.id("username"));
return element;
}

Figure 235 Code Sample

Functional Encapsulation for password input:


public static WebElement txt_sfpwd(WebDriver driver){
element = driver.findElement(By.id("password"));
return element;
}

245

Author Copy. Not For Distribution.


Narayanan Palani

Figure 236 Code Sample

Enter Login code in below section4:

Figure 237 Code Sample

Once code is written, overall page object factory looks like the below
screenshot:

246

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 238 Code Sample

Page object factory:


package pomfunctions;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPOM {
private static WebElement element = null;
public static WebElement txt_sfusername(WebDriver driver){
element = driver.findElement(By.id("username"));
return element;
}
public static WebElement txt_sfpwd(WebDriver driver){
element = driver.findElement(By.id("password"));
return element;
}

public static WebElement btn_sfLogin (WebDriver driver){


element = driver.findElement(By.id("login"));
return element;
}
}

247

Author Copy. Not For Distribution.


Narayanan Palani

Navigate to test scripts (main java file of test cases) and import this page
object factory:

Figure 239 Code Sample

Figure 240 Code Sample

Once entire line of code written in main java file, it looks like the below
screenshot:

248

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 241 Code Sample

Lines of Code entered in test case to login:


package salesforcepack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import pomfunctions.LoginPOM;

public class Contacts_Salesforce_TestCase1 {


private static WebDriver driver = null;
public static void main(String[] args){
System.setProperty("WebDriver.chrome.driver","E://AutomationProject/
/Training//SalesforceTestAutomation//BrowserDrivers//chromedriver.ex
e");
driver = new ChromeDriver();
driver.get("https://login.salesforce.com");
LoginPOM.txt_sfusername(driver).sendKeys("Narayanan@narayanan.co
m");
LoginPOM.txt_sfpwd(driver).sendKeys("HelloWorld");
LoginPOM.btn_sfLogin(driver).click();
driver.quit();
}
}

249

Author Copy. Not For Distribution.


Narayanan Palani

References
 Guru99. (2016, September 10), Page Object Model (POM) & Page
Factory in Selenium: Ultimate Guide [Web log post]. Retrieved from
http://www.guru99.com/page-object-model-pom-page-factory-in-
selenium-ultimate-guide.html
 LAKSHAY SHARMA. (2016, September 10), Page Object Model |
POM [Web log post]. Retrieved from http://toolsqa.com/selenium-
WebDriver/page-object-model/

Resume Guide for Selenium Experts


Writing resume is an art and it needs good amount of efforts to list
expertise in minimal set of lines; This section explains about common
keywords used in Selenium Job Requirements which will help job seekers
for selenium oriented jobs.
Before getting into 'Resume Writing Techniques', it is important to
make out how a profile has been shortlisted in job portals and the reason
behind only few people getting multiple interview calls when you have
desired skill set?
Although your resume may have good list of contents and is one the
best written but if you did not include certain keywords such as
WebDriver, TestNG etc. it may not be sorted by the search engine
algorithm of job portals.
Methods to create a perfect job oriented RESUME to upload for
Selenium Automation Jobs online using portals:
1. Search Job Portal or the email lists with most used words in the Job
description Contents and list them such as:
a. Selenium
b. Experience in Automation
c. Cucumber
d. TestNG
e. SOAP/SOAP UI
f. REST/Restful/Rest API
g. RSpec,
h. Capybara,
i. SQL etc
2. Once identified, include them in your Resume in a structured
paragraph within relevant work experience section.
3. Every morning amend, edit or re-upload the RESUME in such a way
that it comes on top of the list when search results shown to the

250

Author Copy. Not For Distribution.


Selenium Webdriver

recruiters (most of the algorithms pick fresh RESUMEs to list on top


in relevant results).
Methods to create a perfect job oriented RESUME for a particular
Job description you received:
1. Search the keywords listed in the Job description and make sure it is
has been included in your RESUME diligently
2. Include the relevant project experience and additional tools used for
the particular technology in paragraphs or bullet points
3. It is always suggested to fabricate separate RESUME for every Job
description rather than using same RESUME for all jobs
The most common questions asked to most of the recruiters are 'Why
my CV (Curriculum Vitae) is not getting short listed?' and 'Why Job
Description (JD) never matches to my CV 100%?' When you like a job
opening, you never get shortlisted. You are not 100% happy about what
is offered to you, even if you get shortlisted.
If you have walked over any of the above questions and cases, this
section can offer you some guidance on the hidden reasons of profile
short-listing tactics and CV claying process.

Few observations:
- most of the job descriptions turn to be the copy-paste from generic
job profiles. Same JD has been used over the period of time mostly
without a word change.
- If the JD is unique and more descriptive, it hardly matches perfectly
to any profile to get shortlisted
To understand this gap, we should know the traceability between JD
and CV

How the CV is made usually?


Every job searching candidate's pattern is to fabricate a good CV and
upload it in portal or apply for the positions available. Irrespective of the
open positions, CV remains same.
Moreover, not all of us can figure out the difference between CV,
Resume and Bio-Data.

251

Author Copy. Not For Distribution.


Narayanan Palani

Figure 242 Type of Profile


Result:
Probability of CV matching to particular JD is very less.

Suggestions:
CVs have to be customized and updated as per the particular job opening
and applied exclusively for the particular role which is described in JD.
Especially every line in JD has to match with the skill set and work
experience of the candidate applied to the job opening

Psychology of CV shortlisting experts:


1. Compare the CV against JD
2. If CV matches to JD, then pick a best CV out of available CVs.
Here comes the complexity of bringing your CV as an outstanding
one among the CVs available across the industry.

Suggestions:
Due to following psychological reasons, digital representations of profile
get more visibility:
1. Visual Display of Profile attracts more than the words in a page
2. Bullet points are always up to the message and better than the
paragraphs

252

Author Copy. Not For Distribution.


Selenium Webdriver

How to make a digital resume in .doc format?


Some of the easy steps to bring up a digital profile in short span of time
are as follows:
1. In order to write an eye catching resume/CV use Publisher File
Template
Link for Publisher Templates:
http://office.microsoft.com/en-
gb/templates/results.aspx?qu=resume&ex=1&av=ZPB&CTT=5
2. Once the Resume/CV designed, covert and save it as .doc or .pdf file
according to the need of recruiter

Useful points:
1. In case the CV is processed by an external consultant to particular
organization, make sure that the consultant/recruiter understood the
CV's strengths and weaknesses as well as the JD itself.
2. It is duly suggested to have a telephonic discussion with the recruiter
on the profile match.

Once the CV is made and it is powerful, what should be the next step?
Edit and update the CV as an ongoing activity 
Your CV is your own sculpture so make sure it represents the best of
your strengths.

List of top skill sets required for automation testers are compared in the
table below:
Technical Skills Functional Junior Senior Automation
Tester/ Automation Tester/Software
Manual Tester Development
Tester/ QA Engineer in Test
(SDET)
Programming Optional Mandatory Mandatory
Languages
(Ruby, Java, DotNet,
C#, Javascript, VB
Script)
Unit Testing Optional Optional Mandatory
(Test Driven
Development)
HTML Optional Optional Mandatory
CSS Optional Optional Mandatory
OOPs Design Patterns Optional Mandatory Mandatory

253

Author Copy. Not For Distribution.


Narayanan Palani

Application Mandatory Optional Mandatory


Knowledge
Domain Knowledge Mandatory Optional Mandatory
Databases SQL, Data Mandatory Mandatory Mandatory
Marts, ETL
Operating Systems- Mandatory Mandatory Mandatory
Windows
Operating Systems- Optional Optional Mandatory
Linux, Mainframe etc
Software Testing Mandatory Mandatory Mandatory
Basics
ISTQB Foundation Mandatory Mandatory Optional
Exam
SDLC Mandatory Mandatory Mandatory
Unit Testing Tools Optional Optional Mandatory
(Nunit, Junit etc)
Test Scenario, Test Mandatory Mandatory Mandatory
Cases, Test Data, Test
Execution
Defect Life Cycle Mandatory Mandatory Mandatory
Documentation Mandatory Mandatory Mandatory
Standards
Coding Standards Optional Mandatory Mandatory
Code Review Optional Optional Mandatory
Selenium WebDriver Optional Mandatory Mandatory
Test Management Mandatory Optional Mandatory
Tools: Quality Centre,
Test Link etc.
Defect Tracking Mandatory Optional Mandatory
Tools: JIRA, Rational
ClearQuest etc.
TestNG Optional Optional Mandatory
Selenium IDE Optional Optional Mandatory
Selenium GRID Optional Optional Mandatory
Package Management Optional Optional Mandatory
using Nuget, Maven,
Ant etc
Version Control using Optional Optional Mandatory
Tortoise SVN, GIT

254

Author Copy. Not For Distribution.


Selenium Webdriver

Resume Evaluation Process for Test Automation Jobs-A Case Study


Step1: Requirement for the Selenium Automation Tester Role posted online
Automation Test Engineer (Selenium and Python)

Job Profile posted by Company KBC Ltd:


Skill Set: Appium, Selenium, Python, Pytest, Manual Functional Testing,
API Automation Testing, SQL, Java Script
Additional Skill set : Java, TestNG, Performance
Job Description:
Test Engineer with 2 to 3 years of experience in mobile and/or web
automation
Experienced in IOS mobile apps automation
Experienced in understanding and development of framework
Good Knowledge in Java Script
Experienced in Functional Testing and writing test cases
Experienced in development of test scripts
Possess good communication
Good Knowledge in executing scripts on AWS Cloud
Experienced in development of Reports
Good Knowledge on Jenkins Continuous Integration Tool

Step2-Resume from Candidate


Now, HR receives the following resume as a response to the above Job
posted online:

RESUME
Name: Confidential
London.
Contact Number: 09990009990
E-mail: abc@abc.com

EXPERIENCE
October, 2014 – present: Proven capabilities through high quality test
scenario and test case design, test execution and test reports. Currently,
on an intensive work experience internship at CHF Labs in central
London. Working under the supervision of the test manager, on live
projects, the internship involves working on various projects using
manual and automation testing, particularly, using Selenium IDE/RC as
well as other tools such as cucumber and eclipse.
PROJECT EXPERIENCE

255

Author Copy. Not For Distribution.


Narayanan Palani

Software Test Analyst (Intern) @ CHF Labs Ltd- London


October, 2014 – Till Date
CHF-Functional Testing Project
 Participating in daily Agile Scrum meetings for day-to-day testing
activities
 Analysing the test requirements and preparation of test scenarios
 Test case preparation with valid description, steps, expected results
and actual results
 Peer review of test scenario and test cases for the testing team
members.
 Functional test execution and updating the test results as pass and fail
status
 Raising defects with valid priority and severity status in defect
tracking tool, tracking it clearly with developers, test lead to update
the defect status
 Performing defect retest and regression testing for the latest defect
fixes
 Worked on Waterfall Model, Agile Methodologies and attended
scrum meetings for day-to-day test activities

CHF Automation Test Project using Selenium IDE, RC with TestNG


 Analysing the test requirements and preparation of test scenarios
 Automation script preparation with valid conditions in Selenium
IDE, Selenium RC and TestNG
 Peer review of test scenario and test cases for the testing team
members
 Automation test execution and updating the test results as pass and
fail status
 Raising defects with valid priority and severity status in defect
tracking tool, tracking it clearly with developers, test leads to update
the defect status
 Performing defect retest and regression testing for the latest defect
fixes
 Gained Skills: Selenium, Java, JIRA, HP ALM, Java-script,
HTML, VBScript, SDLC

EXPERTISE
 Preparation of test case documentation
 Test case execution

256

Author Copy. Not For Distribution.


Selenium Webdriver

 Adhering to and ensuring that the best practice of software testing


standards are being observed
 Test Planning & Strategizing
 Test Scheduling
 Defect Management & Reporting
 Following and understanding the principles of the Software
Development Life Cycle (SDLC)
 Knowledge/understanding of programming languages (Java,
VBscript, HTML etc.)
 Use of automated test tools and test management tool, particularly
Selenium IDE, Cucumber, Eclipse and JIRA, HP ALM (Application
Life Cycle management by HP)

SKILLS
 Ability to write test scenarios from any given requirements
 Proficiency in writing accurate test cases
 Paying attention to detail when it comes to tracking defects
 Ability to compile good and accurate test reports
 Comfortability in SQL and ability to create, update, modify and
delete records
 Savvy understanding of VBscript, HTML, Java, Javascript and OOPs
 Efficaciously implementing Selenium IDE automation for web-based
functionality testing
 Deep understanding regarding both Manual and Automation
software testing and considerable talent in achieving targets

EDUCATIONAL QUALIFICATIONS
2006-2010 St Antony College/ University of San Diego
 BSc (Hons) Computing and information Systems
 Specialized in network engineering and telecommunication systems
 Project Work: Designed a mobile application for cinema reservations
and bookings by the help of Java Micro Edition as the main software
and other supporting software

2002-2004 Cambridge institute of management


 Diploma in Institute for the Management of Information Systems
(IMIS)
 Specialized in financial and cost accounting, hardware maintenance
and Desktop trouble shooting

257

Author Copy. Not For Distribution.


Narayanan Palani

 The Foundation Diploma included Microsoft office, other Microsoft


packages and application packages/utility programmes such as
Dbase.

Reference
Available on request

Step3: Resume Evaluation Checklist


HR and Subject Matter Experts review the Resume and update the
checklist below:

Resume Evaluation Checklist Yes/No


2 to 3 years of experience in mobile automation NO
2 to 3 years of experience in web automation YES
Experienced in IOS mobile apps automation NO
Experienced in understanding and development of
framework YES
Good Knowledge in Java Script YES
Experienced in Functional Testing and writing test
cases YES
Experienced in development of test scripts YES
Good Knowledge in executing scripts on AWS Cloud NO
Experienced in development of Reports YES
Good Knowledge on Jenkins Continuous Integration
Tool NO
Python Scripting Experience NO
Final Decision-Resume Shortlisted? NO

Future of Test Automation Roles or Software Testing Roles


Software Testing and Test Automation has been involved various growth
in the past twenty years and it has been continued to be in the 'Early
Growth' stage of Industry Life Cycle.
Growth of Selenium Web Driver related Google search is increased
and overtaken QTP based search from Sept'2015 onwards:

258

Author Copy. Not For Distribution.


Selenium Webdriver

Figure 243 Google Search Results

Reference:
 https://www.google.com/trends/explore?date=all&q=selenium%20W
ebDriver,QTP&hl=en-GB

What is the observation from the graph?


Interested testers towards open source tools such as Selenium are
increased comparing to paid tools such as QTP (Unified Functional
Tests), and there is an expected and incremental demand for Selenium
Web Driver in near future.

How the Software Tester Roles evolved in the past?


Software Testing Industry has developed with wide range of Manual
Testers, Test Managers and few Automation Testers in different domains
such as Banking, Finance, Security, Insurance, Embedded, Telecom,
Hardware Technologies, Database, CRM Applications, Healthcare and
Government etc.
In current testing industry (since2010), these functional testing roles
(such as Manual Test Engineer, Test Engineer etc) are evolved and
developed to following roles (not limited to):
1. Subject Matter Experts (who knows Functional Testing)
2. Business Analyst (who knows UAT [User Acceptance Tests] )
3. UAT Testers
4. Manual Testers (perform Test Case Design, Test Execution and Test
Reporting)
5. Defect Managers
6. Localization Test Engineers

259

Author Copy. Not For Distribution.


Narayanan Palani

7. ETL Test Engineers [Extract, Transfer, Load: ETL]


8. Test Automation Engineers:
a. Automation Engineer (performs general test automation, design
and execute test scripts)
b. Software Developer in Test (performs Automation Framework
Design, Test Automation Platform Design, Test Scheduling,
Test Execution and Test Reporting)
c. Automation Test Managers
9. Test Managers

What are the well expected growth dimensions of Test Automation


Engineers in near future?
Since Test Automation evolved to the stage where testing teams are in
need of segregating and exclusive task allocation of automation tasks to
experts in respective specialties which leads to following job roles within
test automation in near future:
1. Test Automation Engineers (SDET):
a. Automation Framework Solution Architect (Designs the
framework and visionary to the test framework structure)
b. Automation Test Results Manager (Designs Test Results DB to
integrate with Automation Engines like Selenium WebDriver
with NoSQL Databases such as MongoDB, CouchDB etc.)
c. Automation Defects Manager (Controls Automated Defect
Raising Capability and Defect Life Cycle of Automation Test
Results which evaluates the duration of defect raise to defect
fixes)
d. Agile Test Automation Manager (Controls sprint-based test
automation activities)
e. Automation Test Utility Engineer (Develops utility scripts to
enhance frameworks such as screenshots, cross browsers, cross
mobile capabilities etc.)
f. Test Automation Migration Expert (Proven experts in
converting test scripts from one tool to another tool)
2. Test Automation Support Engineers:
a. Test Developers (who support testing team to bring new
utilities/automation tools, provide object lists, descriptions to
help testers in developing frameworks)
b. Test Results Analysis Engineers (to develop OCR kind of
models to analyse and find defects on test results to raise
defects with the help of automated code)

260

Author Copy. Not For Distribution.


Selenium Webdriver

c. Test Automation Middleware Engineers (to write scripts to


control middleware, APIs involved in Integration Tests)
d. Test Automation Quality Auditor (to control test activities with
respect to international standards such as Lean, Six Sigma,
CMM Level5 and perform frequent Auditing and deliver
reports to bring an advanced quality in testing deliveries)

Interviews of Selenium Test Automation Roles


When testers are invited for Interviews on Technical Roles, at least 1 to 3
rounds of technical discussions are followed by 1 to 2 HR and Project
Managers discussion planned by Testing Teams. Based on the
organization and structure, these rounds differ to each other. This
section illustrates the methods preparing for such technical automation
interviews with relevant preparation.
Minimum one to two technical rounds and one final HR round
expected in test automation role related interviews.

Pre-Interview Project Submission:


Most of the companies in UK and USA go through this approach of
sending a project case to the shortlisted candidates and in turn receive the
sample automation scripts to evaluate their technical skills.
Some of the companies used to deliver the sample project details
and URL to automate or application to automate through recruiters; once
the scripts are written along with answers for multiple choice questions,
next the candidates are asked to share the solutions/answers to companies
through recruiters or the job portal of the organization. Candidates are
invited for the first round of technical interview based on the evaluation
post-project submission.

Some useful reference at this stage: It is instructed to use the following


GITHUB page to 'download zip', the fully built selenium frameworks
and start-up the scripting process on the framework to submit project
solutions as soon as possible:

http://github.com/narayananpalani/testautomation
These well built frameworks will reduce the chances of rework to a great
extent and at the same time will assist you to get the solutions ready in
few hours.

Topics on First Technical Round


 General Testing Questions

261

Author Copy. Not For Distribution.


Narayanan Palani

 Defect Life Cycle


 Software Testing Life Cycle
 Agile Methodology, Sprints, Daily Stand up Meetings
 Project-based Questions
 Domain-based Questions
 Testing Team Problem Solving Questions on Complex
Situations

Some useful references at this stage:


ISTQB Question Answers and blogs from testing experts at:
http://www.testingminded.com/2010/04/top-100-software-testing-
blogs.html

Some of the queries to be written to prove the SQL skills such


as:
 Create Table, Insert Records
 View all Records, Select Records
 Structure of Table
 Delete Records
 Inner Join (Including Left Inner Join, Right Inner Join)
 Outer Join (Including Left Outer Join, Right Outer Join)
 Drop Database, Index, Table and their differences

Some useful references at this stage:


Search google.com with following inputs: "sql commands
filetype:ppt"

Topics on Second Technical Round


If Selenium is the tool required as per job specification (JD),
 General Selenium Questions
 Specific Code-based Selenium Questions
 Sample scripts for certain uses of Automation Framework
 Automation Framework Architecture and how to build one for
the team?

Some useful references at this stage are given in Appendix A


Experience of Test Automation
Implementing automation frameworks in testing projects need ample
amount of project experiences and opportunities to comprehend various

262

Author Copy. Not For Distribution.


Selenium Webdriver

challenges involved in the setting up of the testing environment. This


section is a space for detailed discussion on test expert's work experience
in implementing various automation frameworks and key points to keep
record in such stages.

Implementation of Selenium Automation Framework in Agile


Projects
Project condition: Newly developed application needed a set of testing
teams to perform System Tests and Integration Tests for every sprints of
Agile Testing Life Cycle. Since the project has started as a new testing
cycle, business expects test automation to be ready and start working
right from sprint cycle1.
Challenge: The reasons which play a vital role in making test
automation tests impossible to launch in sprint 1 in most of the projects
are as follows:
 Due to the progression of the developers with the code base, the
object lists are not available for the web pages.
 In order to facilitate the unit tests, the set of objects are getting
changed and renamed repeatedly.
 Manual test cases are not ready for the test cycle.
 Automation framework is not built yet.
 No Proof of Concept has been provided on any automation tool.

Implementation Stage1
When sprint 1 functional test cases are prepared, that is the perfect time
to select right automation framework for the project and perform Proof
of Concept (refer the PoC section to understand sample steps). During
the Sprint 1 manual test execution, PoC and Automation Framework
design, automation of sprint 1 manual (functional) tests can be performed
during Sprint1-so these test cases can be executed as 'Regression Tests'
in cycle2 onwards.

Implementation Stage2
Once automation framework has been implemented and performed with
few test cycles, this time is considered as ideal to use schedulers such as
Jenkins or Hudson and schedule overnight tests. If parallel test execution
is possible, it can be implemented in multiple test environments
successfully and lessen the overall test execution time.

263

Author Copy. Not For Distribution.


Narayanan Palani

Implementation Stage3
Agile projects reach the stage where the test results load into hundreds of
folders which results in difficulty to maintain and identify similar test
results. So this time ideal to implement test results repositories such as
MongoDB to store the results direct from automation framework.

Implementation Stage4:
If the automation framework is developed, implemented and scheduled
to run in multiple test beds/target machines, it is ideal to reuse the same
set of frameworks for performance tests with the help of Openstack or
other environmental setup.

Why Software Testing is Necessary and Mandatory for Software


Projects?
Few years ago, software glitch has been identified in a particular flight
model xxvi and the software issue results in power failure of the flight
immediately while travelling on the air. If this problem is associated with
just one flight, it is an impact rather than a major affect across the world.
But the software glitch has to be fixed across 230 airliners in order to
rectify the problem sooner.
Do you think it would have been prevented if found earlier in the
flight design? If you say 'yes' then that is the main reason behind the
necessity of software testing.

Let us take a next step to understand how the impact affects the whole
project:
Case1:Mark has been designing a mobile device software from initial
releases and never identified any defect by himself during the
development. He has released the product to market and identified
negative customer feedbacks on certain features as not working at all.
Though Mark has fixed the problems (known as 'bugs' or 'defects') and
released to the customers again in the market, do you think he will
receive the same reputation and enthusiastic approach from his clients
what he had received in the past? Answer: No.
After few months, customers returned with new set of defects and
complained about the invisibility of certain contacts and gallery images
as those have been lost from their phones, and at the same time, the
inability in installing any new application in their devices and so on.
How many times Mark can fix the problems and go back with the new
excuses?

264

Author Copy. Not For Distribution.


Selenium Webdriver

Case2: After learning from the failures of the first product, Mark brought
Anderson into the project to perform testing activities. Now, Anderson
made sure of the proper validation of the mobile device software (called
as 'tested') and most of the problems (known as 'defects') were identified
and resolved (known as 'fixed'), then the mobile device was released to
the market.
Do you think the mobile device is free of any defect now?
The answer is No! As the existence of a defect free product is beyond the
bounds of possibility (as an assumption made to help every software
tester).
The mobile device may come back with further failures but those
failures are limited to the scope of something Anderson missed to find
during his testing activities.
Case3: 'Palani', an another software tester, was introduced by Mark to
the testing team and he worked along with Anderson and found some
more bugs. Do you think the mobile device is defect free now? (Since
Anderson performed a test and found some bugs them the rest of the
bugs which were missed by Anderson were later detected by Palani,
hence, both of them found all the failures of the mobile device software.)
The answer is same as the answer of Case2. No matter how many testers
testing the software, the defects may exist and remain unidentified even
after testing (but majority of the critical defects and major issues would
have been identified and fixed during the testing process since the new
defects may affect with low priority).

Bugs, Defects, Issues, Failures, Errors, Problems, Mistakes, Faults-


Do they hold the same meaning?
Answer: No!
Case4: Anderson wanted to test the feature of calling a new contact
from the mobile device using the android latest version. Instead of
pressing the call button, he pressed contact details button which led him
to view the full contact details, hence, thought he is unable to make a
call. Palani heard it from Anderson and tried to make a call by pressing
the call button and the phone was ringing in the other end.
What has happened to Anderson‘s test? It is called ‗Error‘
Rule: ‗A human action that produces incorrect result‘ is known as
‗ERROR‘.
Case5: Anderson pressed the message button to send message to one of
the contacts and it displayed the 'call history' rather than displaying the
message box to type the messages.

265

Author Copy. Not For Distribution.


Narayanan Palani

What has happened to Anderson‘s test? It is called ‗Fault‘ or ‗Defect‘ or


‗Bug‘ or ‗Issue‘
Rule: A manifestation of error in software
Note: This fault can lead to failure when executed (see the next
example).
Case6: Palani tried to save a new contact and he saved the contact
successfully. When in the contact list, he searched for the newly added
contacts, he did not find the new contacts which he added.
What has happened to Palani‘s test? It is called ‗Failure‘
Rule: Deviation of the software from its expected delivery of service
How does the software defect harm people, environment and company?
Software glitch (defect) of the airline causes the accidents and affects the
people flying on board, and thus, it impacts the whole airline industry
and gives negative brand name to the organization providing the service.
Defect of the mobile device software reduces the sales and brand
name of the company, hence, Mark, Palani and Anderson may have to
look for other opportunities if the project fails to produce stability in a
mobile device. if any new defect is occurred after releasing the software
to the mobile devices, the main impact is on the customer satisfaction.

Impact of the Defects-Case Study on Mars Climate Orbiter


Martian Atmosphere and climate have been observed by Mars Surveyor
Program‘98 through Mars Climate Orbiter with the help of ground-based
computer software which produces in metric units of newton-seconds (N
s)xxvii.
This software failed to produce the output in prescribed format and
rather produced the outputs in non-SI units (instead of metric units of N
s); hence, communication with the spacecraft has been totally lost (due to
the incorrect output of ground-based computer, spacecraft travelled in
orbital insertion). The cost of the mission was $327.6 million total for the
orbiter and lander and imagine the amount of loss due to the defect found
in ground-based computer software.
These kind of defects are classified as ‗highly critical‘ since the
impact caused major lose to the cost of the project.

Importance of Reliability in Software Testing


The reliability of software testing can be defined as the probability that
Application Under Test (AUT) will not cause the failure or defect for a
specified time in specific condition.
But across the globe, some open questions have been raised from
testing professionals.

266

Author Copy. Not For Distribution.


Selenium Webdriver

Can an AUT be defect free?


Always a basic assumption has been made that software has bugs and no
software is defect free, hence, the answer is ‗No‘.
If there is a defect-free software, do you rely on the software or if
the software is reliable to customers?
Though it can be a defect-free software but there is no guarantee of
its reliability to its end users or customers, hence, the answer is ‗No‘.
If the software has the highest rate of reliability, do you expect to see the
defects within the software in such situation?
One of the world leading mobile devices is highly reliable and loved
by customers across the globe. At the same time, the device also contains
few bugs existing in the softwarexxviii.
So if the software or the product is reliable, it doesn't mean it is
defect free. Hence, the answer is ‗Yes‘.
Let us take an example from non-software products:
World large seller of healthcare products has been highly trusted and
identified as reliable in health care sectors. But the defective products
have been identified in some situations and the particular product has
been recalled which led to major losesxxix.

What is Software Testing?


―Software testing is a set of processes aimed at investigating, evaluating
and ascertaining the completeness and quality of computer software.
Software testing ensures the compliance of a software product in relation
with regulatory, business, technical, functional and user requirements.
Software testing is also known as application testingxxx‖
―An investigation on the product or service to improve the quality and
find defects to report to stakeholdersxxxi‖
―A process of executing a programme or application with the intent of
finding the software bugsxxxii‖
―Software testing is a method of assessing the functionality of a software
programmexxxiiii.‖
―Software testing is the process of evaluating a software item to detect
differences between given input and expected outputxxxiiv.‖
Though there is no set of generally accepted terminologies and
guidelines worldwide, it is possible to refer the most valued glossary of
software testing which are available onlinexxxv.
Set of detailed glossaries is provided onlinexxxvi to facilitate the beginners.

267

Author Copy. Not For Distribution.


Narayanan Palani

Why Defects Occur in Software?


Software is written by information technology professionals who are
human beings and are not devoid of committing errors. So mistakes are
obvious on their part in some point of time in any of the work undertaken
by them.
Human errors are common and are expected to be a part of the
software when developed. But it costs more when identified late within
the software projects.
Case1: How easy it is to cure to Cancer disease in the earlier stages?
As per the researchxxxvii, there is a high probability of survival if the
disease is diagnosed and treated as earlier as possible.
Similarly, how easy it is to fix the defect within the software in the
earlier stages?
Very easy: After reading the Software Requirement Specifications
(SRS), Anderson identified incorrect flow and spelling mistakes within
the feature names so he discussed with business analyst Rajavarman.
Rajavarman was agreed with the mistake within the requirement and
corrected it in the next version of the SRS document; hence, this
incorrect feature is no longer existing in the project. If Anderson had
missed reading about this incorrect feature here, he would have identified
in later stages which would have made Martin (developer) to fix the code
changes and it would cost Anderson to again spend more time to retest
and identify its workability as required standards. But all this work have
been diminished and removed just by finding the fault in the document
review itself.
Refer: Design in the graph below. It is just 1x time of the total cost of
the project taken by the defect fix.
Easy: Anderson testing the software which is under development process
recently, and he identified a bug. It is easy for Martin (Developer) to fix
it immediately and release the next version of code.
Refer: ‗Implementation‘ in the graph below. It is just 6.5x times of the
total cost of the project taken by the defect fix. Expensive defect
comparing to the defects found in Design stage.
Difficult: Anderson testing the software before releasing to the
customers, and he identified the bug. But the software has to be delivered
within a week. Now, Martin has to fix the code and release to Anderson
and he has to test and prove that the defect is not appearing anymore. All
this has to be conducted within a week.
Refer: ‗Testing‘ in the graph below. It is just 15x times of the total cost
of the project taken by the defect fix. Expensive defect comparing to the
defects found in Design and Implementation stages.

268

Author Copy. Not For Distribution.


Selenium Webdriver

Very Difficult: Software has been released to customers and some of its
functionalities were not found in workable condition. Now, Anderson
tested it within his test environment according to the customer‘s
identification and realised that the bug is valid and needs to be fixed
soon. Martin has no other option than releasing a new version of the
software to customers with all the problems rectified.
Refer: ‗Maintenance‘ in the graph below. It is 100x times of the total
cost of the project taken by the defect fix. Expensive defect comparing to
the defects identified in earlier stages.

Phase in Software Development Relative Costs to Fix the


xxxviiii
Defects
Design 1
Implementation 6.5
Testing 15
Maintenance 100

If Developer has strong development experience, why are the


defects still happening in the software projects?
Martin has been working in developmental roles for the past twenty-
five years and held a strong background of code development. But on the
other hand, Anderson has been identifying some high priority bugs
within his code in every cycle of the software project.
The primary reason for these defects is the ‗time limit‘.
To deliver the code, ‗Under Increasing Pressure‘ and ‗Tight project
time lines‘, a genuine mistake within the code is plausible.

269

Author Copy. Not For Distribution.


Narayanan Palani

How to rectify it?


Anderson has to be good enough to be trained in software testing and test
coverage to identify bugs in its earlier stages of the software testing life
cycle.

Software Testing-Four Key Objectives


Every test activities hold exclusive objectives and purposes to conduct
list of test activities. But software testing itself has its own highest
standards within the objectives and followed by every test specialist in
testing projects. Some of them are listed here:
 ‘Finding Defects’:
Attitude of test specialists (comparing to developers) are found to be
more defective and defended that the software has a lot of bugs in every
test cycle. The defects are getting fixed to improve the quality of
software. (not just raising the defects and leave it to developer‘s hands. It
is tester's responsibility to follow up on the defect and ensure that the
defect is getting fixed.)
When high quality defects are raised or identified by the testers,
they receive attention from test managers, development team and
management of the organizations.
 ‘Gaining Confidence about the Level of Quality’:
Key stakeholders of the software projects are the business owners who
trust on testers for their testing quality. Development managers
coordinate with testing team to get the list of defects and get it fixed with
the efforts of the developers. Then, testing team is requested to retest the
fixes and ensure its functionality as updated to the present standards
(retested). Hence, a lot of trust and value are evaluated on tester's profile.
Testing managers manage and support entire testing team and watch out
to help in every testing activity, hence, gaining confidence of testing
team manager is the first priority for the tester, and then, the trust from
project owner, development manager and key project managers are the
key objectives of any test specialist.
 ‘Providing Information for Decision Making’:
Software test specialists are expected to provide a well written defect
with all possible and relevant details about the defects during the test
performance. When test reports are submitted to business owner, it
should be meaningful, understandable and not cumbersome for non-
technical stakeholders.
 ‘Prevent Defects’:
Identification of the defects is one of the sole objectives and preventing
such defects from being occurred in testing projects in all possible ways

270

Author Copy. Not For Distribution.


Selenium Webdriver

such as review requirements and correcting the issues in documentation,


hence, further defects can be eliminated.
Case1-Experience of Test Specialist:
There were some key defects raised with clear information on failures in
one of the business critical applications for customers and the defects are
under review process by business owners. They requested to have a
detailed discussion on why such defects are raised. Post-detailed
discussion, those defects led the project owners to take decision on
stopping the project and redesigning the entire code of the software to
deliver the high quality software to the customers. At the same time, this
activity created a tension around development team (due to rework and
unnecessary defects causing performance issues around developer's code
quality); hence, most of the developers are curious to reduce such defect
raising activity in future test cycles. So development team started
coordinating with testing team members closely to review Software
Requirement Specification, Design Documents which provided
opportunities to testers on reviewing documents and providing their
concerns and issues which are rectified immediately with the help of
project owners; hence, further defects are prevented.
When the software came to retest in testers‘ hands, it has been
logged with further defect lists to get them fixed by developers. This
story continues until getting supreme quality on the software within the
given span of time. This process of raising high quality defects (no
matter if developers concern on it or not) led to receive award from
project owners on best individual contribution.

How Testing and Debugging are different?


Let us take the example of Cancer Treatments: PET Cancer Scan
conducted to patients to identify the stage of the respective patients xxxix
and then specialist in radiology or nuclear medicine analyze more on the
medical test results and understand what kind of treatments are required
to cure the patients. So both performing scan and analysing the test
reports are two different activities and scan has to be performed prior to
analysing the test report.
Similarly, software is tested by test specialists and defects are listed
in software test results. Developers review the test results and investigate
(debug) the code on the location of the error to fix the issues to resolve
the failures, hence, testing and debugging are two different activities.
Testing is to be done prior to debugging and both are done by two
different specialists (tester: testing and developer: debugging).

271

Author Copy. Not For Distribution.


Narayanan Palani

How much Testing is enough?


If you assume that you have got a new functionality (example: Message
Box in Mobile ) to test and found three hundred functional test cases
available within the project, and now, you need to test this new
functionality within two working days with the use of four mobiles as per
the communication with the Project Manager.
Following are some of the important questions running in your mind:
1. How many test cases have to be tested?
2. How many defects can be identified possibly in these two days?
3. Is it possible to cover entire new functionality and related
functionalities within these two days?
4. Why I have to test only in two days when there are three hundred test
cases still to perform on the software?
5. How can I make sure that all the possible defects are identified and
the functionality is working as expected in the given budget of four
mobiles and two days?
6. What are the calculations that I have to make in order to perform
these two days tests successfully?
The best suggestion is to pick the relevant test cases and run them for
two days and identify its potential defects. If 45 test cases are relevant to
message functionality (which has a high risk of finding new defects) and
20 additional test cases are relevant modules (may have defects due to
the new functionality introduced), I would go ahead and test 65 tests
within two days by splitting the work as 40 test cases per day. (There is a
question on why 40 per day when 65/2 is 33: The real reason is to have a
back up time for raising defects and retesting those defects on day 2 if
possible)
So what matters in deciding this ‗how much testing is enough‘?
Answer:
i. Level of Risk including Technical and Business product and project
risk
ii. Project constraints such as time and budget
So what are not really matters when deciding ‗how much testing is
enough‘?
iii. Size of Testing Team
iv. Size of the Development Team

Software Testing Principles


1. Software Testing explores presence of defects

272

Author Copy. Not For Distribution.


Selenium Webdriver

Though organizations value testing teams and their quality of defects


raised in the testing projects but there is an important point mentioned:
Do you think that developers don't know how to raise defects and find
bugs within the software applications? Of course, they know it, but
testers are the experts in finding the defects. If you are riding a bike on a
packed road, do you think that you don't know traffic rules? Still, why
traffic constables are appointed to monitor the traffic? This is to control
the vehicles and monitor travellers on their activities. Similarly,
developers do know how defects are identified, but testers are the strong
and potential specialists to identify defects and manage those defects
until getting fixed.
The first priority question is to realize why software testing and
testing teams are required for a software project team? In fact, many
start-up companies and small software companies' projects are getting
delivered without even properly tested by software testers. Few start-up
companies do not own testers within their software teams but the reality
of high quality exist within software projects when testers are recruited
with high quality background.

2. It is not possible to test exhaustive


An approach to test all possible combinations used for testing is known
as Exhaustive testing. Anyone would prefer to test completely in such a
way that all possible tests are covered, hence, full testing completion
gives the satisfaction to business owners. But it cannot be considered as
the right angle to look at the complexity.
It not only takes long time to test 'Exhaustive Testing', but it is not a
suggested testing approach.
Why?
If you test the hotel booking application online, travellers may book
and use the application in ten thousand possible ways probably, but if
you have decided to test the entire combinations,
- How many resources are there to be deployed?
- How much cost involved?
- If any defects identified, do you repeat the complete combinations of
exhaustive testing?
- Do you think market don‘t change until you test complete
combinations and release the product?
Due to complexities mentioned above, specialists always go in favour of
important test combinations and relevant test combinations rather than
testing everything (hence, exhaustive testing is impossible).

273

Author Copy. Not For Distribution.


Narayanan Palani

 What are the best approaches/options used to avoid exhaustive


testing?
- Risk Analysis: Understand what are the high risk areas to test?
- Priorities: High/Medium/Low priority functionalities and pick
high/relevant functionalities and medium/low whenever required.

3. Early Testing
Why the test should be performed early and why such approach required
when development takes long time to prepare the software?
The actual answer is related to the defects and how fast those
defects are needed to be fixed?
If the defects are identified earlier that gives a healthy environment
of bringing high quality software on time.
Case1: Aravind is the leading software tester for the enterprise software
who has been given the duration of seven weeks to test the software in
seven cycles (one week per cycle).
He has found three minor/low priority defects for six cycles and
identified two major/high priority bugs in the last week. Thus, project
manager is left with remaining just 6 days to get the defects rectified and
fixed. But the valuable questions are as follows;
- When Aravind is going to retest the fix and ensure that the fix is
working as expected?
- If he finds the fix is open and needs to be fixed again, how many
more days it takes to fix, retest and prove that the latest fix is
working fine?
Due to the situation above, there is a fair chance of extension in the
delivery date of the software for further testing and it impacts overall
cost and customer satisfaction on the late delivery of the software.
What needs to be done to avoid the situation of late delivery of the
software and last minute defects?
Test Early!

4. Defect Clustering
―Small number of modules contain high number of defects and lead to
operational failure‖
Case1: Rajavarman tests 20 modules of ABC bank‘s payment system
and found 55 defects within the account details module itself. The total
number of defects found in the entire functional testing is 57 which show
that the number of defects within account details module is higher than
19 other modules.

274

Author Copy. Not For Distribution.


Selenium Webdriver

These issues cause the operational failures, hence, his manager


Srinivasa suggests to perform a Defect Retest of all 55 fixes of the
defects and repeat the tests on account details module to 100% coverage.
This is to ensure that the account details are working as expected and no
more bugs are introduced by fixing the 55 defects, hence, this particular
module is clustered with high number of defects. Defect clustering
creates the alarm to test management to concentrate more on the specific
modules to validate and ensure the capturing and fixing of all the defects
before proceeding to the next stage of the testing process.

5. Pesticide Paradox
―If same tests are being repeated in every Regression Cycle, the chances
of the occurrence of new defects in AUT is less.‖
Case1: Jagan looked after the automation tests and has designed 1800
automation test cases using selenium to run in every drop of the product
release. He is recycling the use of the same tests for every drop (as
expected in Regression Tests).
In the very first drop, he found 130 defects which has become single
digit of defects in further drops. In fact, Drop 19 produced no defect after
his Regression Test Execution. The real question is relying on the test
cases and when they are really designed. If the test cases are not updated
over time, there is no point of reusing them as the expected defects are
already raised or discussed with development team, and there is no use of
this automation test pack, hence, this situation is a named as pesticide
paradox. Jagan started updating the test scripts to match with the latest
user stories and run them as part of test cycles which led him to identify
new defects. Thus, redesigning and improving is the ideal solution for
pesticide paradox.

6. Testing is Context Dependent


Case1: Karthick has been working for medical software in government
hospitals and his work is to validate the softwares used for scanning
equipments. Similarly, Apoorv is working on the testing team of
‗scanning equipment ordering system online‘ to contact vendors and
distribute the machines across different hospital branches. Though both
of them deal with scanning system related software, Karthick‘s work is
critical and dealt differently than Apoorv‘s testing process due to the
safety-critical software involved in medical domain where as Apoorv‘s
work is pretty much related to eCommerce/CRM applications. So the test
cycles followed and reviewed process involved in both the testing
activities are different in nature.

275

Author Copy. Not For Distribution.


Narayanan Palani

7. Absence of Errors Fallacy


Case1: John Trench is a test lead for the telecommunication projects
which are involved in 3G technologies. His is assigned with the work to
deliver the quality reports and list of defects identified. Due to the
unwanted situations, project deadline was crossed and he delivered list of
defects only after 3 weeks of deadline provided. The situation at the
customer front has been moved towards 4G and there remains no need of
3G-based software systems what John has been getting his team to work
on. Hence, no matter how much defects/errors are reported in a test
cycle, if it is not relevant or useful in the way customers wanted, it is the
situation known as Absence of Errors Fallacy.

Failure Mode and Effects Analysis (FMEA)


Testing teams are loaded with complex defects and number of defects
with high severity and high priority are always differed on day-to-day
basis. If a testing team wants to control the failures effectively and
provide perfect delivery to customers, it has to be thought on the
implementation of innovative methods such as FMEA: Failure Mode and
Effects Analysis.
This model is used to prioritize the defects based on Severity level,
Repeatability (Reproducible or not), likelihood of the defect and impact
over the business. Severity, Reproducible Probability and Detection
Probability can be evaluated from 1 to 10 in a scale and estimated for
FMEA analysis as given below:

FMEA
Failure Mode and Effective Analysis
Process Name: Registration Page Testing Activities of Test Team A
Process Number:000234
Date:XXYYZZZZ
Revision:01
Risk
Probability of Probability
Failure Severity Preference
Occurrence of Detection
Mode (A) Number
(B) (C)
(RPN)

276

Author Copy. Not For Distribution.


Selenium Webdriver

Rate 1-10
Rate 1-10 in
in which Rate 1-10 in
which 1 is Calculation
1 is least which 1 is least
least and 10 of A*B*C
and 10 is and 10 is most
is most
most
Defect1:
Failure to 10 2 4 80
Login
Defect2:
Issue in
8 4 4 128
Colour
Code
Defect3:
Failure to
2 6 5 60
Submit
the form
Defect4:
Server
Error on
10 4 8 320
the
HTTP
Response

Risk Preference Number (RPN) is the multiplication of all three


factors of scale once evaluated; hence, RPN provides the final points for
each defect to see which defects are to be picked with top priority.
Case study: Carefully looking at the figures in the table above proves
that the Defect 4 is in high priority due to high RPN value. In probability
of reproducing the defects, Defect 3 leading among the listed defects, but
overall RPN is high for defect 4. There are two defects having high
severity (defect 1 and 4), but defect1's RPN is lesser than defect4's RPN
value.

Who defines the scaling factors of RPN?


Cross Functional Teams and Subject Matter Experts discuss to evaluate
each defect and update the scaling factors to arrive at RPN. In Agile
Projects, Scrum discussions are carried out to analyse defects to calculate
RPN and prioritize for each sprints within test project scope.

277

Author Copy. Not For Distribution.


Narayanan Palani

How does Automation Tests help FMEA?


When automation tests are designed and segregated with High, Medium
and Low priority as part of Regression Automation Suites, severity can
be predetermined for those tests, and respective severity can be applied
to future defects without further discussions. Hence, it assists in easy
spotting of RPN value with a rapid speed comparing to manual tests.
Also FMEA is a quick solution to include Defect Retest scripts within
automation frameworks based on RPN values.

Risk Based Testing


Carrying out software testing activities by considering risk as the primary
theme of the project is Risk Based Testing which aims to identify
potential risky defects and improve the quality of the Application Under
Test by fixing such high risk defects.

Understanding Risks:
Risks are the uncertainties expected in future with probability of
occurrence and expected potential losses as outcome, hence, it impacts
the software testing projects, and right mitigation actions are expected to
take care to overcome such risks. Risks can be anything which cause the
losses such as financial losses or losses of customers or even the
corporate brand image damage to the product.
Identifying loss making risks and controlling with right action plan
are the key elements in every software testing project.
Formula:
Risk=Damage to the project*Probability or Occurrence
Example:
Risk of the Login Failure of Web Page within project AB=Lost of 800
CAD per failure*10 times occurrence expected in current
year=8000CAD Loss due to the Risk for the current year

When Risk Based Testing is considered as a Best Fit?


If the projects are facing challenges due to time, cost, resource,
environment, hardware or frequently changing requirements or anything
which challenges the project delivery, this result in implementing Risk
Based Testing to such projects to carry out testing by considering those
risks as primary motivator to the project.
Case1: AB Ltd is short of 140 lakhs to carry out last phase of the testing
project to complete Regression Tests, hence, Test Manager Helen
Mitchell decided to implement Risk Based Testing to carry out limited
number of high risk test cases within the time of the test execution.

278

Author Copy. Not For Distribution.


Selenium Webdriver

Case2: Mobile Product company is planning to release next version of


the android phone which will attract at least 1.2 billion buyers across the
world. But there is a potential risk that the defect identified earlier while
testing that causes damages to at least three functionalities of the mobile
features, and they are consistent failures as well. Henceforth, the testing
team has been following Risk-based approach on those high priority
defects and on their defect fixes and testing around the affected features
to get released in the next 3 weeks time.

Types of various risks and their potential impact:


Every risk has been carefully identified, analysed, classified and
controlled before actual execution of the programme.

Following are some of the important classification of risks:


 Schedule Risk:
Failure to meet the deadlines of delivery is a crucial risk in software
projects. There are many critical aspects of what can go wrong when
tests are estimated?
Incorrect calculation of time estimation leads to extending the
project time to complete the test cycles and less customer satisfaction.
When resources are not monitored and controlled, project delivery get
affected due to unexpected leaves causing absence of resources, no or
irregular training causing poor performance, irregular management result
in less productivity etc.
Failure to identify high priority defects and finding such important
defects in the last minute leads to delay in the testing cycle completion.
Especially project scope has to be determined in the initial stage of the
project and amendment of such project scope (usually common in
complex customer projects) creates additional test scope for the testing
team.
Note: Refer ‗Software Automation Testing Secrets Revealed‘ Publishing
Date 12 Feb 2016 - Chapter 7: Test Estimation on various Test Estimates
and respective calculation.
Case: Surendar Singh, a test manager of Aditi Solution Tech. Ltd. has
planned three weeks testing of 15 working days to complete the testing
cycles of approximately 850 test cases. It has been planned as follows:
850/(15*4)=14 test cases per person/per day, henceforth, he has targeted
at least 15 test cases to be performed to meet the deadline. Paul from the
team has gone in surprise leave on the very first week for 4 days and this
would have affected 4*14 test cases =52 test cases of the project in a
particular module. As a twist to the story, another team staff has gone in

279

Author Copy. Not For Distribution.


Narayanan Palani

sick leave for two days in the middle of the test cycle which created
additional backlog of 28 test cases on top of 52 existing backlogs, and
Surendar has no other option than increasing the duration of the project
at the last week which has created tension around the delivery date. This
situation shows a clear example of poor planning from the test
management. If leaves were organized earlier and Surendar had planned
at least 16 working days of tests to include 2 days as backup, then it
would have sort out the leave issues on time. Because the total backlog
of tests 80 (means 52+18) would have executed with the help of last
working day availability.

 Budget based Risk


Test manager estimates budget for the complete testing assignments and
proposes the total cost to the project management. If such budget is gone
wrong in any possible way, it impacts with high risk to the project
delivery.
When project expenditure has been increased due to number of
defects raised in the last cycle of the testing, it is fairly possible that the
risk is very high to the project and it may affect the delivery of the
project after testing.
Especially, increasing project scope during the testing cycles creates
additional impact on the ongoing project and increasing risk of failure to
high.
Case-wrong budgeting: Rachael has been looking after her testing team
for the last three years and her estimation has never gone wrong at all. As
a test lead, she looked after the complete six member automation testing
team and there is no test manager in the start up organization. She
estimated budget of 200 million for the next agile testing project which
span across seven months duration in the end of the next year. When the
project started, there was a resource constraint and increased license fee
for test automation tools (just few days ago when extending the licenses)
which caused 43 more million to the overall testing budget, and
eventually, it resulted in getting the work outsourced from a new partner
of the organization (which is the decision taken by the owner of the
organization). The primary reason for the wrong budgeting is not the
incorrect calculation but the preparation of budget one year before the
actual project being initiated which created the huge gap between
expectation and reality.
Case-Cost Overrun: Satyadip is the project manager who looks after
testing team‘s cost and budget estimation, and his estimation of budget
overrun due to the hardware problems of the project and additional
hardware are required in order to continue testing. Senior managers of
280

Author Copy. Not For Distribution.


Selenium Webdriver

the organization denied to allow any further cost in addition to the


planned budget of Satyadip, which is a critical risk to the project and the
testing activities are put on hold until the approval has been given to buy
and replace the existing repaired hardware. The real mistake is not fully
on the budget but on the investigation before arriving at the final
calculation of the budget. It is suggested to get the hardware reviewed by
technical engineers on their steady state and warranty period in order to
include hardware costs to the budget.
Case-Project Scope Expansion: Business Analyst of the Mobile
Automation Testing Project raises the alarm to stakeholders that the
scope of the project is now increased due to new regulations of the
telecommunication department of government. Now, the test manager of
the project, Mr. Lahiri, suggests the increase of 23 million in the overall
test automation programme for the next two years due to this impact. So
the real cause to this high risk of increased cost is due to socio-political-
economical-legal-technical impacts (called S.P.E.L.T).

 Operational Risk
Software testing projects plan to improve the quality standards by
implementing industry‘s best practices as new set of processes. If there is
a mistake in implementing such processes, it creates lot of expenses to
overall project budgeting. Hence, such operational risks lead to project
failures in most of the occasions.

How Risk-Based Testing is benefited with Automation Tests


A number of Automation Tests with various priority, severity
combinations help automation team to choose right set of test suites to
run in test cycles. Also automation frameworks are the straight solutions
to adapt as part of Risk-Based Testing rather than choosing 100%
manual testing to complete tests which doesn‘t fit to short time in most
of the projects.

Migration Strategy from UFT to Selenium


As per the industry leaders and market survey results xl, Selenium will be
the de-facto in test automation industry by 2020 and most of the
organizations switch from different licensed and open source automation
tools to selenium to maintain their QA program up and running with
latest industry standards; When resources are widely available with
selenium skill set, it would be fairly easy to recruit selenium based test
engineers to automation test teams rather than waiting for limited
resources who are equipped with different or old automation test tools.

281

Author Copy. Not For Distribution.


Narayanan Palani

When test teams move from different testing tools to selenium, there are
two main challenges faced:
1. Choosing right method of migration to test automation tool (code
conversion or rewrite scripts)
2. Choosing right programming language
When two automation test tool frameworks scripted with different
programming languages, it will be an expensive attempt to convert the
code from one programming language to other and fix the code to get it
worked; Also it has a direct impact on Return On Investment (ROI) and
reduce the profit from test automation projects.
Instead converting the code using code conversion tools from
VBScript to Java (for example), it is always suggested to take the
opportunity to review the automation scripts and rewrite to the new
automation tool.
For example, majority of the web automation test frameworks are
developed using HP UFTxli (Unified Functional Testing) [formerly QTP]
in recent years. If testing teams decided to convert VB Script based UFT
code to Selenium based Java Automation Framework, it would be an
expensive attempt.
It is possible to migrate the VB Script based UFT Automation
Framework scripts to VBSWebDriverxlii which is a VBScript bindings for
Selenium 2! In this way UFT Automation Framework can easily be
migrated and components/functions reused in Selenium Automation
Framework in VBScript programming language!
But the real question comes to picture on desktop applications based
test automation; Since Selenium set of tools support only web based test
automation, this is one of the leading open question in recent years.

How to migrate the desktop application based UFT (formerly QTP)


scripts to Open Source Tools?
Of course it is not possible to migrate desktop application based test
automation scripts to Selenium WebDriver or any selenium tools
(situation until Sept'2016). But there are two open source projects
developed known as twin, white and used by leading companies to
address this challenge. Especially 'Twin' has been designed based on
Selenium WebDriverxliii

'Twin' Tool:
Details of the project explained more in the location given below,
https://code.google.com/archive/p/twin/
Download and use the project from following github location,

282

Author Copy. Not For Distribution.


Selenium Webdriver

https://github.com/JamesMGreene/twin

'White' Tool:
Download and use the project from following github location,
https://github.com/teststack/white
Wiki page to understand build and FAQ,
https://github.com/teststack/white/wiki

Following are the summary of this chapter:


Title: Automation Tool migration
Current Automation Test Tool: HP Unified Functional Testing (formerly
Quick Test Professional)
'Possible Automation Test Tool' to automate/migrate web based
automation scripts: VBSWebDriver
'Possible Automation Test Tool' to automate/migrate desktop
applications based automation scripts: Twin or White

Type of Current Automation Proposed Automation


Application Test Tool and Test Tools with
Under Test (AUT) Programming Programming Language
Language
Desktop HP Unified Functional Twin using
Applications Testing (UFT) using Java,DotNet,C# (or White)
VBScript Language
Web Applications HP Unified Functional VBSWebDriver using
Testing (UFT) using VBScript Language
VBScript Language

Note:
For more information on Twin and White tools, please listen to Q&A
part of following talk,
Simon Stewart (2016 September 14),Learn Using Selenium 3 0 [Youtube
Video] Retrieved from https://www.youtube.com/watch?v=bistojJPR98

283

Author Copy. Not For Distribution.


Narayanan Palani

Few Final words

Selenium WebDriver based Automation Frameworks are widely used


across testing projects in different models and features. But it is advised
to understand at least one automation framework in order to design and
build using necessary JAR files. It takes few days to complete a technical
software book but it takes at least four to sixteen weeks for practising
such tools to get better comfort over test scripting.
Since Ant, Maven and Jenkins are covered along with framework
setup steps in Part1 of this book, they are not repeated.
As part of Part2, few examples are covered to facilitate readers with
better knowledge and industry-based learnings but there are wide variety
of scripts available in github.com which are listed as part of Appendices
A and B for your reference.
If you have enjoyed reading this book, please feel free to provide
full stars and write comments in the page where this book has been
purchased. If you are not happy or content with the book and expected
more concepts to be covered up, requesting you to write to me on
LinkedIn messages, so I can take the points and cover them as part of
Part3.

284

Author Copy. Not For Distribution.


Selenium Webdriver

Appendix A

List of popular Selenium Interview Question & Answer blogs are,


 https://www.quora.com/Where-can-I-find-interview-questions-
for-Selenium-web-automation#
 http://www.software-testing-tutorials-
automation.com/2014/09/selenium-WebDriver-interview-
questions_16.html
 http://www.software-testing-tutorials-
automation.com/2014/01/selenium-WebDriver-interview.html
 http://www.softwaretestinghelp.com/selenium-interview-
questions-answers/
 http://career.guru99.com/top-30-selenium-interview-questions-
answers/
 http://www.slideshare.net/mikkyjames/selenium-interview-
questions-and-answers-h2kinfosys
 http://roadtoautomation.blogspot.com/2014/05/WebDriver-
selenium-interview-questions.html
 http://seleniummaster.com/sitecontent/index.php/introduction-
to-selenium-automation/selenium-automation-job-skills-
menu/24-selenium-automation-job-interview-category/112-
seleniumWebDriverandseleniumideinterviewquestions
 http://www.qaquestions.org/selenium-interview-questions/
 http://learn-automation.com/selenium-interview-questions-and-
answers/
 http://modernpathshala.com/Learn/Selenium/Interview
 http://www.interviewquestionspdf.com/2016/03/top-80-
selenium-interview-question.html
 http://www.testingexcellence.com/test-automation-interview-
questions-and-answers/

Use some of the well built and available selenium frameworks to


practice and explain the framework oriented questions from,
Java Based Selenium Frameworks Available:
 https://github.com/jaypee2286/Java-SeleniumSample
 https://github.com/pathimanoj/Google/tree/master/google

285

Author Copy. Not For Distribution.


Narayanan Palani

 https://github.com/im-zeeshan/serenitybdd-automation-
framework/blob/master/src/test/resources/stories/AcceptanceTe
stSuite/Capability/Feature/STR101-LookupADefinition.story
 https://github.com/techGen/WebDriver_Framework
 https://github.com/rkumar2131/MineSweeperAutomation
 https://github.com/SkillsFundingAgency/specflow-selenium-
framework/tree/master/Specflow_Selenium_PO_Example2/Fea
tures
 https://github.com/irishshagua/web-automation-sample-
framework
 https://github.com/hemano/Automation_FW_Cucumber
 https://github.com/agalyad/WebDriver_Java_TestNG_Ant
C# Based Selenium Frameworks Available:
 https://github.com/michaelthecsguy/PayoffAutomationJUnit
 https://github.com/kapilsethi/AutomationUsingWebDriverAnd
PageObjectPattern
 https://github.com/agalyad/WebDriver_C_NUnit
Java Script Based Selenium Frameworks Available:
 https://github.com/Matt-B/cucumber-js-selenium-WebDriver-
example
Python Based Selenium Frameworks Available:
 https://github.com/gowtham88k/selenium_python
 https://github.com/Rosalita/Selenium
 https://github.com/hermanwahyudi/selenium/
 https://github.com/shahriarqureshi/Python
Ruby Based Selenium Frameworks Available:
 https://github.com/testwisely/agiletravel-ui-tests
General Selenium Related Frameworks Available:
 https://github.com/jenglezou/chilaca
 https://github.com/yuliabro/WebDriver
 https://github.com/3vilvetal/WebDriver/tree/master/HelloWorld
 https://github.com/camiloribeiro/cello
 https://github.com/IntelligentSigma/selenium-test-automation-
framework
 https://github.com/axatrikx/axa-framework
 https://github.com/Webaib/Selenium-LWF
 https://github.com/Natalya11444/Cucumber-Selenium-JUnit-
Test-Framework

286

Author Copy. Not For Distribution.


Selenium Webdriver

 https://github.com/Natalya11444/Selenium-TestNG-Test-
Framework
REST API Based Selenium Frameworks Available:
 https://github.com/kvyasHacks/APITestAutomationFramework
/tree/master/nasa-test-base
 https://github.com/lnikod4s/automation-selenium-testing-
framework
 https://github.com/michaelthecsguy/PayoffAutomationJUnit
Appium Based Framework Available:
 https://github.com/agalyad/iOS_Appium_Java
Selenium using Excel VBA -Projects Available:
 https://codingislove.com/browser-automation-in-excel-
selenium/
 https://github.com/florentbr/SeleniumBasic
 http://www.makeuseof.com/tag/how-to-automate-firefox-or-
chrome-with-vba-and-selenium/
 https://www.youtube.com/user/xtremeExcel/search?query=sele
nium
Excel VBA and Internet Explorer Based Automation
Framework Available:
http://automatetheweb.net/
Selenium Queries can be answered at:
 http://grokbase.com/g/gg/selenium-users

287

Author Copy. Not For Distribution.


Narayanan Palani

Appendix B

Examples for successful automation builds using Selenium


WebDriver:
 https://github.com/jaypee2286/Java-SeleniumSample
 https://github.com/pathimanoj/Google/tree/master/google
 https://github.com/im-zeeshan/serenitybdd-automation-
framework/blob/master/src/test/resources/stories/AcceptanceTestSuit
e/Capability/Feature/STR101-LookupADefinition.story
 https://github.com/techGen/WebDriver_Framework
 https://github.com/rkumar2131/MineSweeperAutomation
 https://github.com/SkillsFundingAgency/specflow-selenium-
framework/tree/master/Specflow_Selenium_PO_Example2/Features
 https://github.com/irishshagua/web-automation-sample-framework
 https://github.com/hemano/Automation_FW_Cucumber
 https://github.com/agalyad/WebDriver_Java_TestNG_Ant

288

Author Copy. Not For Distribution.


Selenium Webdriver

Appendix C

This section explains about the list of changes within the toolset of
selenium in each version. This information may not be accurate at times
as the changes may have been quick and suggesting readers to go
through http://www.seleniumhq.org/ for clear information. This table is
given as an abstract based on the recent webinars in the year 2016 by
Simon on Selenium 3 and other references from the URLs given below

References
 Simon Stewart (2016 May 26),Selenium 3 0 Retrieved from
https://www.youtube.com/watch?v=gS4ZqLpA9r4
 Simon Stewart (2016 September 14),Learn Using Selenium 3
0Retrieved from https://www.youtube.com/watch?v=bistojJPR98
 W3C (2016 September 14),World Wide Web Consortium from
https://www.w3.org/
 SeleniumHQ(2016 September 14),Selenium from
https://www.seleniumHQ.org/

289

Author Copy. Not For Distribution.


Narayanan Palani

Selenium 1 Selenium 2 Selenium 3 Selenium 4

Expected during
Christmas
(of 2016 or 2017)
Release Period

[as per the To Be


2004 2009-2011
presentation 'using Discussed
Selenium 3 0 by
Simon in Eurostar
Conference']
Selenium Selenium
IDE, WebDriver,
Selenium
Selenium Selenium IDE,
WebDriver, Selenium
Tools

Core, Selenium RC,


Selenium IDE, W3C, Appium
Selenium Selenium Core,
Appium [for [for mobile]
RC, Selenium Server,
mobile]
Selenium Appium [for
Server mobile]
Jason WebDriver
Huggins- introduced and bind W3C
Project tight with Beginning of W3C WebDriver
Manager for underlying web compliance Protocol server protocol
Selenium browser;Object is used
Core Oriented
Internationally
W3C compliant agreed
Firefox is connected
Table Based WebDriver standards are
with the help of
Runner server:Gecko Driver followed and
firefox extensions
is used for Firefox Gecko Driver
will be used
Internet Explorer's
Advantages

Selenium
HTML Table- COM object
Selenium Core WebDriver is
Selenium collection used to
removed planned to be
IDE communicate for
removed
tests
Legacy Selenium
RC libraries can be
used as leg-rc
Chrome, Opera
Three extended to used as (but it is highly
columns part of WebDriver recommended to
tests. move from
Selenium RC to
Selenium
WebDriver)
Selenium Introduced Jason
Core' Wire Protocol
Designed by representing

290

Author Copy. Not For Distribution.


Selenium Webdriver

Jason for commands for


Time and Firefox Driver
Expenses
System
Since there
were defects
from Internet
Explorer,Firef
ox,Opera for
Selenium Core
the Javascript
Project integrated
Application
with WebDriver
(Time and
project hence it is
Expenses
become Selenium
System), he
WebDriver
decided to run
the tests in
Javascript and
drive the
application
Incredibly
difficult to
manage table Challenge-not
Only Java 1.8 or
based possible to analyse
higher versions are
scripting source code of IE
supported.
hence and other browsers
Selenium RC
introduced
Selenium RC
scripts written
in multiple
languages and
communicate
Disadvantages

to Selenium Every browser


Server and follow different
this Server wire protocol-
has internal Challenge for
communicatio WebDriver
n (core
protocol) to
Selenium
Core
Javascripts.
Scripts Browsers are
running in become more
Javascript complicated in
Sandbox is a every version hence
real challenge Selenium decided to
hence use W3C for next
integrated version(in selenium
with 3.o)

291

Author Copy. Not For Distribution.


Narayanan Palani

WebDriver in
next
version(in
selenium2.o)
Selenium
WebDriver:
Guarenteed
Selenium IDE:
Guarenteed
Selenium RC:
Limited [Since
Selenium
Selenium Core is
Life Span

Core:
removed in
Limited [Not
selenium 3 onwards,
used in
scripts are to be
Selenium 3.o
migrated to
onwards]
Selenium
WebDriver]
Appium:
Guarenteed [Not yet
migrated to
Selenium 3.o as on
Sept2016]

292

Author Copy. Not For Distribution.


Selenium Webdriver

Appendix D

Part 1:

Figure 244 Software Automation Testing Secrets Revealed

293

Author Copy. Not For Distribution.


Narayanan Palani

Software Automation Testing Secrets Revealed, is recommended for


those aspiring to be experts or advanced users by Automate Software
Applications using
 Selenium Web Driver using Java,
 Selenium Web Driver using Dot Net,
 Selenium IDE,
 AutoIT,
 Cucumber,
 Specflow,
 BDD,
 TDD,
 Jenkins,
 NUnit,
 ReportUnit,
 XSLT Reporting,
 Maven,
 Jason Phantom Ghost Driver,
 TestNG,
 JUnit,
 Ant,
 Eclipse,
 Team Foundation Server,
 Visual Studio,
 HP Unified Functional Testing (formerly Quick Test Professional),
 Ranorex,
 IBM Rational Functional Test,
 Excel VBA Automation,
 Excel Objects Automation,
 SOA Testing-SOAP UI Automation,
 ETL Testing and SQL Testing for Agile-Continuous Integration.

References
 Aravind. (2016, September 07). Software testing tutorials and
automation [Web log post]. Retrieved from http://www.software-
testing-tutorials-automation.com/p/selenium-WebDriver.html
 Syam. (2015, January 29). XLS Reading for DDF [Web log post].
Retrieved from http://pssqtp.blogspot.co.uk/2015/01/xls-reading-
for-ddf.html

294

Author Copy. Not For Distribution.


Selenium Webdriver

 zhaozhiwen (2016, June 16). 手把手教你搭建数据驱动测试框架


[Web log post]. Retrieved from
http://www.jianshu.com/p/206654aeae29
 Matt,B. (2016, June 30)cucumber-js-selenium-WebDriver-example
[Web log post]. Retrieved from https://github.com/Matt-
B/cucumber-js-selenium-WebDriver-example
 Dave H@tourdedave ,elemental-selenium-tips [Web log post].
Retrieved from https://github.com/tourdedave/elemental-selenium-
tips
 Guru99. (2016, September 10),How to use Locators in Selenium IDE
[Web log post]. Retrieved from http://www.guru99.com/locators-in-
selenium-ide.html
 Guru99. (2016, September 10),All About Excel in Selenium: POI &
JXL [Web log post]. Retrieved from http://www.guru99.com/all-
about-excel-in-selenium-poi-jxl.html
 LAKSHAY SHARMA. (2016, September 10), FindElement and
FindElements Command [Web log post]. Retrieved from
http://toolsqa.com/selenium-WebDriver/findelement-and-
findelements-command/
 Ellie Skobel. (2016, September 10), Selenium Minutes [Web log
post]. Retrieved from http://seleniumminutes.com/
 Guru99. (2016, September 10), Page Object Model (POM) & Page
Factory in Selenium: Ultimate Guide [Web log post]. Retrieved from
http://www.guru99.com/page-object-model-pom-page-factory-in-
selenium-ultimate-guide.html
 LAKSHAY SHARMA. (2016, September 10), Page Object Model |
POM [Web log post]. Retrieved from http://toolsqa.com/selenium-
WebDriver/page-object-model/
 AMAL BOSE. (2016, September 12), 8 Selenium IDE Plugins you
Should be Aware OfRetrieved from http://axatrikx.com/selenium-
ide-plugins/
 LogToolBar,ScreenShotOnFail,PageCoverage Plug-ins are designed
by Samit Badle
 Selenium IDE is designed by Jason Huggins, Adam Goucher, Shinya
Kasatani, Dave Hunt, Samit Badle
 Selenium IDE Plugins section from
http://www.seleniumhq.org/download/ can be referred for multiple
useful Plugins to use as part of Selenium IDE tests
 Google. (2016, September 20), Google Trends. Retrieved from
https://www.google.com/trends/

295

Author Copy. Not For Distribution.


Narayanan Palani

 TestNG (2016 September22)Annotations [Web log post]. Retrieved


from http://testng.org/doc/documentation-main.html#annotations
 Aravind (2016 September22)Example Of Difference Between
@Before/@After VS @BeforeClass/@AfterClass In JUnit With
WebDriver [Web log post]. Retrieved from http://www.software-
testing-tutorials-automation.com/2014/03/example-of-difference-
between.html
 StackOverflow2016 September22)Difference between BeforeClass
and BeforeTest in TestNG [Web log post]. Retrieved from
http://stackoverflow.com/questions/30587454/difference-between-
beforeclass-and-beforetest-in-testng
 Ram Mokkapatty(2015, February28) TestNG DataProvider Example
[Web log post]. Retrieved from
https://examples.javacodegeeks.com/enterprise-java/testng/testng-
dataprovider-example/
 Guru99. (2016, September 22), All About Excel in Selenium: POI &
JXL [Web log post]. Retrieved from http://www.guru99.com/all-
about-excel-in-selenium-poi-jxl.html
 Andreas Ebbert-Karroum. (09/07/10), File Downloads With
Selenium — Mission Impossible? [Web log post]. Retrieved from
https://blog.codecentric.de/en/2010/07/file-downloads-with-
selenium-mission-impossible/
 Hitesh Singh, (2012,August 14), Selenium Web, Mobile Automation
and for Complete Automation Tutorials using WebDriver [Web log
post]. Retrieved from
http://silenumnmisc.blogspot.co.uk/2014/08/connection-between-
through-mongodb-and.html
 artoftesting(2016,September24) MongoDB Automation in Java[Web
log post]. Retrieved from
http://artoftesting.com/automationTesting/mongoDBAutomation.htm
l

W
i
TechCity UK(2016, September 24) TechNation Visa Scheme [Web log
post]. Retrieved from http://www.techcityuk.com/tech-nation-visa/
ii
NARAYANAN PALANI. (2016, September 14), Certified Member
Profile[Web log post]. Retrieved from
http://www.ibm.com/certify/profile?palanin6
iii
UNICOM. (2016, September 14), India Testing Awards 2016[Web log
post]. Retrieved from

296

Author Copy. Not For Distribution.


Selenium Webdriver

http://www.unicomlearning.com/2016/India_Testing_Awards/index.html
iv
NARAYANAN PALANI. (2016, September 14), LinkedIn[Web log post].
Retrieved from https://uk.linkedin.com/in/narayananpalani
v
DOCUMENTS.MX, (2016, September 14), ADCOM 2009 CONFERENCE
PROCEEDINGS[Web log post]. Retrieved from
http://documents.mx/documents/adcom-2009-conference-proceedings.html
vi
Matthew Dwyer, (1997), Software Management Spring 1997[Web log post].
Retrieved from
http://people.cs.ksu.edu/~dwyer/courses/748/resources/cmm-
tr25/tr25_l3g.html
vii
Stress Marq, (2016, September 14), 5 Free Image Analysis Software Tools
for Microscopy[Web log post]. Retrieved from
http://www.stressmarq.com/5-free-image-analysis-software-tools-for-
microscopy/?v=79cba1185463
viii
Matthew Dwyer, (1997), Software Management Spring 1997[Web log post].
Retrieved from
http://people.cs.ksu.edu/~dwyer/courses/748/resources/cmm-
tr25/tr25_l3c.html
ix
Matthew Dwyer, (1997), Software Management Spring 1997[Web log post].
Retrieved from
http://people.cs.ksu.edu/~dwyer/courses/748/resources/cmm-
tr25/tr25_l3b.html
x
Matthew Dwyer, (1997), Software Management Spring 1997[Web log post].
Retrieved from
http://people.cs.ksu.edu/~dwyer/courses/748/resources/cmm-
tr25/tr25_l3a.html
xi
Matthew Dwyer, (1997), Software Management Spring 1997[Web log post].
Retrieved from
http://people.cs.ksu.edu/~dwyer/courses/748/resources/cmm-
tr25/tr25_l4b.html
xii
Matthew Dwyer, (1997), Software Management Spring 1997[Web log post].
Retrieved from
http://people.cs.ksu.edu/~dwyer/courses/748/resources/cmm-
tr25/tr25_l4a.html
xiii
Matthew Dwyer, (1997), Software Management Spring 1997[Web log post].
Retrieved from
http://people.cs.ksu.edu/~dwyer/courses/748/resources/cmm-
tr25/tr25_l5c.html
xiv
Ranorex GmbH., (2016,September 24),Ranorex [Web log post]. Retrieved
from http://www.ranorex.com/
xv
IBM(2016 September24),Rational Functional Tester[Web log post].
Retrieved from http://www-03.ibm.com/software/products/en/functional
xvi
http://selenium-release.storage.googleapis.com/3.0-beta2/selenium-java-
3.0.0-beta2.zip
xvii
AutomatedTester, (2016,September 14), mozilla/geckodriver[Web log post].
Retrieved from https://github.com/mozilla/geckodriver/releases
xviii
http://chromedriver.storage.googleapis.com/index.html
xix
http://selenium-release.storage.googleapis.com/3.0-beta2/selenium-java-

297

Author Copy. Not For Distribution.


Narayanan Palani

3.0.0-beta2.zip
xx
philip@armorgames.com, (2011,October 26), sessionId should not be null;
has this session been started yet? #2716[Web log post]. Retrieved from
https://github.com/seleniumhq/selenium-google-code-issue-
archive/issues/2716
xxi
Yatendra Goel, (2009,September 13), Selenium - Exception while executing
selenium.stop()[Web log post]. Retrieved from
http://stackoverflow.com/questions/1417666/selenium-exception-while-
executing-selenium-stop
xxii
Matej Tymes, (2016,APRIL 19), Matej Tymes's Weblog[Web log post].
Retrieved from http://matejtymes.blogspot.co.uk/2014/10/WebDriver-fix-
for-unreachablebrowserexc.html
xxiii
Cheryl Feldman,Keir Bowden,Nick Hamm. (2016,September 14),[Web log
post]. Retrieved from https://trailhead.salesforce.com/
xxiv
Cheryl Feldman,Keir Bowden,Nick Hamm. (2016,September 14),[Web log
post]. Retrieved from
https://trailhead.salesforce.com/trail/getting_started_crm_basics
xxv
Youth by mind not by age(2014 September 17),Learn how to open Package
explorer tray in any Eclipse version;Retrieved from
https://www.youtube.com/watch?v=x_oeur6_0jw
xxvi
UPI.COM. (2015,May 02):"Boeing finds software glitch in 787 that can cut
jet's power in flight[Web log post]. Retrieved from
http://www.upi.com/Top_News/US/2015/05/02/Boeing-finds-software-
glitch-in-787-that-can-cut-jets-power-in-
flight/4271430546448/?spt=sec&or=tn
xxvii
Wikipedia, (2016,September 14), Mars Climate Orbiter[Web log post].
Retrieved from https://en.wikipedia.org/wiki/Mars_Climate_Orbiter
xxviii
BALASUBRAMANYAM SESHAN, (2011,October20), Forget the Hype:
10 Defects of Apple iPhone 4S That You Overlooked[Web log post].
Retrieved from http://www.ibtimes.com/forget-hype-10-defects-apple-
iphone-4s-you-overlooked-324822
xxix
BALASUBRAMANYAM SESHAN, (2011,October20), Forget the Hype:
10 Defects of Apple iPhone 4S That You Overlooked[Web log post].
Retrieved from http://www.ibtimes.com/forget-hype-10-defects-apple-
iphone-4s-you-overlooked-324822
xxx
TECHOPEDIA, (2016,September 14),Software Testing [Web log post].
Retrieved from https://www.techopedia.com/definition/17681/software-
testing
xxxi
WIKIPEDIA, (2016,September 14),Software Testing [Web log post].
Retrieved from https://en.wikipedia.org/wiki/Software_testing
xxxii
istqbexamcertification.com, (2016,September 14), [Web log post]. Retrieved
from http://istqbexamcertification.com/what-is-a-software-testing/
xxxiii
Whatis.com, (2016,September 14),Software Testing[Web log post].
Retrieved from http://whatis.techtarget.com/definition/software-testing
xxxiv
(2016,September 14),Software Testing[Web log post]. Retrieved from
http://www.codeproject.com/Tips/351122/What-is-software-testing-What-
are-the-different-ty
xxxv
TESTINGSTANDARDS, (2016,September 14),Glossary of terms used in
software testing[Web log post]. Retrieved from

298

Author Copy. Not For Distribution.


Selenium Webdriver

http://www.testingstandards.co.uk/bs_7925-1_online.htm
xxxvi
TESTINGSTANDARDS, (2016,September 14),Glossary of terms used in
software testing[Web log post]. Retrieved from
http://www.testingstandards.co.uk/living_glossary.htm
xxxvii
Cancer Research UK, , (2016,September 14), [Web log post]. Retrieved
from http://www.cancerresearchuk.org/about-cancer/cancer-
symptoms/why-is-early-diagnosis-important
xxxviii
iSixSigma, (2016,September 14),[Web log post]. Retrieved from
https://www.isixsigma.com/industries/software-it/defect-prevention-
reducing-costs-and-enhancing-quality/
xxxix
Cancer Research UK, , (2016,September 14), [Web log post]. Retrieved
from http://www.cancerresearchuk.org/about-cancer/cancers-in-
general/tests/pet-scan
xl
Michael (2016 August 25)TAKING YOUR SELENIUM TESTS FOR WEB
AND MOBILE BEYOND YOUR LOCAL FIREFOX BROWSER[Web log
post]. Retrieved from
http://www.jug.ch/html/events/2016/selenium_tests.html
xli
HP(2016 September 24),Unified Functional Testing (UFT) [Web log post].
Retrieved from http://www8.hp.com/uk/en/software-solutions/unified-
functional-automated-testing/
xlii
henrytejera @ gmail dot com (2016 September 23)VBS WebDriver Just a
VBScript bindings for Selenium 2. [beta] Current version is 1.0.0 Beta [Web
log post]. Retrieved from http://htejera.users.sourceforge.net/vbsWebDriver/
xliii
Google code(2016 September 24)Twin,Paragraph4 [Web log post].
Retrieved from https://code.google.com/archive/p/twin/

299

Author Copy. Not For Distribution.


Author Copy. Not For Distribution.

Anda mungkin juga menyukai