25,19 €
Get writing tests and learn to design your own testing framework with Selenium WebDriver API
Selenium WebDriver is a platform-independent API for automating the testing of both browser and mobile applications. It is also a core technology in many other browser automation tools, APIs, and frameworks. This book will guide you through the WebDriver APIs that are used in automation tests.
Chapter by chapter, we will construct the building blocks of a page object model framework as you learn about the required Java and Selenium methods and terminology.
The book starts with an introduction to the same-origin policy, cross-site scripting dangers, and the Document Object Model (DOM). Moving ahead, we'll learn about XPath, which allows us to select items on a page, and how to design a customized XPath. After that, we will be creating singleton patterns and drivers. Then you will learn about synchronization and handling pop-up windows. You will see how to create a factory for browsers and understand command design patterns applicable to this area.
At the end of the book, we tie all this together by creating a framework and implementing multi-browser testing with Selenium Grid.
This book is for software testers or developers.
Pinakin is a BE(Computer Science) with 17+ years of IT experience which includes development and test automation experience. I am PMP and ISTQB certified. He is currently working at Intellect Design Arena as an automation architect. He handles the automation framework creation and maintenance effort in various projects. Previously, Pinakin has worked at Patni, Accenture, L&T Infotech etc. Following are some of the prestigious clients for which Pinakin has worked, General Electric, Bellsouth Telecommunications, Albertsons Retail,Travelers Insurance, Harleysville insurance, Barclays,Bank of Santander, Bank of Montreal, HSBC, CITI, Canadian Imperial Bank of Commerce,HDFC. Pinakin has used tools like QTP, Winrunner, UFT and now working with Selenium WebDriver.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 169
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Kunal ChaudariAcquisition Editor:Siddharth MandalContent Development Editor:Smit CarvalhoTechnical Editor: Sushmeeta JenaCopy Editor: Safis EditingProject Coordinator:Hardik BhindeProofreader: Safis EditingIndexer: Mariammal ChettiyarGraphics:Alishon MendonsaProduction Coordinator: Aparna Bhagat
First published: October 2018
Production reference: 2051118
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78961-248-6
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.Packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.Packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Pinakin Chaubal is a BE (Computer Science) with more than 18 years of experience in the IT industry. He is a PMP-certified professional and has worked with employers such as Patni, Accenture, L&T Infotech, and Polaris. He is currently working as a automation architect at Intellect Design Arena Ltd. (the product wing of Polaris). He has designed several frameworks using various techniques, including hybrid, keyword-driven, Page Object Model, and BDD, with Cucumber and Java. He has written one independently published book on Page Object Model using Selenium WebDriver and Java. He has been a reviewer for two books published by Packt. He has his own YouTube channel called Automation Geek, which covers various concepts related to testing and automation.
Nilesh Kulkarni is a staff software engineer, currently at PayPal. Nilesh has extensive experience of working with Selenium. Nilesh has developed frameworks on top of WebDriver in different programming languages and is an open source contributor. Nilesh has actively worked on PayPal's open source UI automation framework, nemo.js. Nilesh is passionate about quality and has worked on different developer productivity tools. He often hangs out on Stack Overflow.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Selenium WebDriver Quick Start Guide
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Code in action
Conventions used
Get in touch
Reviews
Introducing Selenium WebDriver and Environment Setup
Technical requirements
Why is test automation required?
Advantages of test automation
Some pointers on Selenium
What's new in Java 8
Lambda expressions and functional interfaces
Functional interfaces
Default and static methods in an interface
The forEach method for a collection
Streams in Java 8
Understanding Selenium RC
What is cross-site scripting (XSS)?
Introducing Selenium WebDriver
Class structure of Selenium WebDriver
Drivers in Selenium
Remote WebDriver
Mobile drivers
Headless browsers
Why do we need headless browsers?
Preparing for the very first script
Installing Java 8
Setting up Eclipse
Downloading Eclipse
Creating a Maven project
Understanding pom.xml
Manual configuration
Creating the first script
Summary
Understanding the Document Object Model and Creating Customized XPaths
Technical requirements
What is the DOM?
WebElements
SearchContext interface 
DOM traversal
Dissecting the By class
The two types of XPaths
Understanding customized XPaths
Customized CSS
An example traversal
Understanding the text() methods
Finding elements within the container element
Best practice
Extracting WebElements dynamically using tagName
Properties file for WebElements
Prerequisites for automating mobile applications
XPaths for mobile applications
Finding XPaths for mobile browser applications
Connecting the actual mobile device
How to use Screencast
Appium Inspector window
How to use UIAutomatorViewer
Mobile locators
What is a WebView?
Introducing the Fillo API
Debugging in Eclipse
Summary
Basic Selenium Commands and Their Usage in Building a Framework
Technical requirements
What are method signatures?
What are Lists in java?
Important methods in Selenium
Some common reusable methods
The difference between quit() and close()
Understanding the keyword driven framework
Concept of Map and HashMap
Bird's eye view of the framework
Introducing the testng XML file
Triggering the testng XML from within the POM XML file
Handling errors while running pom.xml
Introducing the log4j framework
Extent Reports
How to use Extent Reports in code?
Summary
Handling Popups, Frames, and Alerts
Technical requirements
Window handles
Fetching the window handles
Understanding the Set interface
A look at the iterator() method 
Modal and non-modal dialog
Modal and non-modal pop-up windows
JavaScript and jQuery alerts
Handling non-modal popup windows
Introducing the switchTo() method
Looking at the getTitle() method
Looping through all open windows using the simple for loop
Handling modal popup windows
Modal and non-modal alerts
Creating JavaScript and jQuery alerts
Handling non-modal jQuery alerts
Handling modal JavaScript alerts
Understanding frames and iframes
Handling mobile app permission alerts
DesiredCapabilities
What is a Desired Capability?
The DesiredCapabilities class
Enabling protected mode settings in Internet Explorer
Learning Chrome options
Learning the Firefox options and the Firefox profile
Learning the Internet Explorer options
autograntpermissions capability on Android
Summary
Synchronization
Technical requirements
What is synchronization?
Synchronization types
Unconditional synchronization
Thread.sleep(long) 
Conditional synchronization
Synchronization at the WebDriver-instance level
Implicit wait
Synchronization at the WebElement level
Explicit wait
Fluent wait
Function keyword
A glance at the JQuery library
A Sample application using JQuery
Tomcat setup
Exposing the JavascriptExecutor
Pitfall – Never fall into one
Summary
The Actions Class and JavascriptExecutor
Technical requirements
Builder design pattern
Selenium WebDriver is based on the JSON wire protocol. This book explores various facets of Selenium WebDriver 3. It introduces Selenium WebDriver 3 in a layman fashion and opens the areas in Browser Automation to the reader.
Starting from a very basic introduction to element locators, the basic Selenium commands are explored and various programs are demonstrated to make the concepts clear. Handling popup windows and alerts is dealt with next, followed by various waiting mechanisms. Then we move on to the Actions class and JavaScript executor. Eventually, we explore the command design pattern, create few components of a Keyword-Driven framework, and learn about the extra locators available in Selenium WebDriver 3.
This book is intended for people who wish to learn Selenium WebDriver from scratch. It can also be used by people working on other automation tools, such as UFT, and want to explore Selenium from the ground up.
Chapter 1, Introducing Selenium WebDriver and Environment Setup, gently introduces the reader to what Selenium is, how WebDriver is different from Selenium RC, and covers how to set up Eclipse.
Chapter 2, Understanding the Document Object Model and Creating Customized XPaths. covers with locator identifying mechanisms and the different ways to find XPath. It also introduces the Fillo API and debugging in Eclipse.
Chapter 3, Basic Selenium Commands and Their Usage in Building a Framework, covers the various Selenium commands and their practical usage. We also see some wrapper methods, which can be useful in designing a framework. We go over extract programs to fetch data from excel based on certain criteria.
Chapter 4, Handling Popups, Frames, and Alerts, covers how to handle modal and non-modal popups. We create some customized HTML pages with JavaScript for this purpose.
Chapter 5, Synchronization, covers the various ways of waiting for page loads, elements to be visible, and jQuery execution to get completed.
Chapter 6, The Actions Class and JavascriptExecutor, takes a look at the what the Actions class and the JavaScript executor are by going through many examples with the examples of HTML pages that we create.
Chapter 7, The Command Pattern and Creating Components, covers the command pattern and explains how we can use it to create a keyword-driven framework. We also learn about Selenium Grid.
Chapter 8, Hybrid Framework, explores TestNG listeners and the WebDriverManager library. We also learn how to create a report from TestNG.xml.
You will need an understanding of OOPs concepts in Java
Start from the first chapter and move chapter by chapter until you feel confident
Keep creating tests and sample pages on which you can test
Work on the exercises in the book.
You can download the example code files for this book from your account at www.Packt.com. If you purchased this book elsewhere, you can visit www.Packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.Packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Selenium-WebDriver-Quick-Start-Guide. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789612486_ColorImages.pdf.
Visit the following link to check out videos of the code being run:http://bit.ly/2CGHvf6
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
<dependency>
<groupId>
com.codoid.products
</groupId> <artifactId>
fillo
</artifactId>
<version>
1.18
</version></dependency>
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
This piece of code will print out
TestCase1
TestCase3
TestCase4
Any command-line input or output is written as follows:
$ mkdir css
$ cd css
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about Packt, please visit packt.com.
Welcome to the exciting world of test automation using Java 8 and Selenium WebDriver 3.x. Throughout this book, we will get up to speed with Selenium and its surrounding technologies. Selenium is a browser automation tool that has progressed tenfold since its initial inception. Along with tools such as AutoIt, it can be used for automating desktop applications. Selenium is getting used extensively in mobile automation nowadays. The most important point is that it is open source, has a vast developer community, and is constantly evolving. With Selenium Grid, we can simulate different browsers on a single machine.
First, we will start with understanding the basics. This chapter is a gentle introduction to Selenium, and we will be covering the following topics:
The need for test automation and its advantages
Java 8 (b
riefly
)
Selenium RC
Selenium WebDriver
Various drivers in Selenium
Preparing for the first script
You will be required to have Java 8, Maven, Selenium WebDriver 3.13, Eclipse Kepler or higher.
The code files of this chapter can be found on GitHub:https://github.com/PacktPublishing/Selenium-WebDriver-Quick-Start-Guide/tree/master/Chapter01
Check out the following video to see the code in action:http://bit.ly/2PqyMEt
Let's get started by understanding why test automation is needed. Today's agile world needs quick feedback on the code's quality. The developers check-in application code in a source code repository like GitHub. It is imperative that these changes be tested, and the best way to do so is through automation. A test-automation suite can eliminate the mundane work of manual regression testing and can be helpful in finding bugs earlier, thus reducing manual testing time. It can be configured to run at a particular time in the day.
A cut-off time should be provided to the developers, such as 6 P.M. in the evening, by which time they should check in code, get the application build done, and the application deployed to a server like Apache Tomcat. The automation suite may be scheduled to run at 7 P.M. daily. Jenkins is a tool that's used for continuous integration, and so can be used for this purpose.
Advantages of test automation include reducing the burden on the testers doing the manual execution so that they can focus on the functional aspects of the application. Generally, a smoke, sanity, regression test suite is created for this purpose. The advantage of having automatic triggering through Jenkins is that it facilitates test execution in an unattended mode.
We will be using version 3.13, which is the latest version of Selenium at the time of writing this book. It has developed a lot from its early ancestor, Selenium 1. Selenium RC was another tool that would let you write automated web application UI tests in programming languages such as Java, C#, Python, Ruby, and so on, against a HTTP website using any JavaScript enabled browser. For the coding part, we will be working with Java 8. Learning with Java can be fun and at the same time, fast.
Up until Java 7, we only had object-oriented features in Java. Java 8 has added many new features. Some of these features are as follows:
Lambda expressions and functional interfaces
Default and static methods in interfaces
The
forEach()
method in iterable interfaces
The Java Stream API for bulk data operations on collections
Don't worry if you find this intimidating. We will slowly uncover Java 8 as we progress throughout this book.
Functional interfaces contain one—and only one—abstract method. An abstract method is one which should have a body in the implementation class if the implementation class is not abstract. It can have any number of regular methods (methods which have a body in the implementation classes), but the prerequisite of a functional interface is that the number of abstract methods must be only one. These interfaces are used hand-in-hand with Lambda expressions.
In the following code block, the demo method is inside an interface Greeting. Therefore, this interface should only have one abstract method, which is the demo method. In order to instruct other users that this is a functional interface, we annotate this interface with the @FunctionalInterface annotation.
The type of blockofCodeA will be of this functional interface type. This annotation is optional:
@FunctionalInterfacepublic interface Greeting { public void demo();}
Up until Java 1.7, it was not possible to define a method inside an interface. Now, 1.8 introduces the default methods through which we can provide implementation for a method inside the interface. Let's see an example of this here:
interface Phone{ void dial(); default void text() { System.out.println("Texting a message"); }}
Static methods in Java are those methods that can be invoked without creating an object of a particular class, provided that the static method is in that particular class. In Java 8, static methods can be defined inside an interface, as shown here:
interface Phone { inx x; void changeRingtone(); static void text() { System.out.println("Texting"); }}public class PhoneDemo { public static void main(String[] args) { Phone.text(); }}
You can invoke the text() method directly using the name of the interface.
