35,99 €
Complement Selenium with useful additions that fit seamlessly into the rich and well-crafted API that Selenium offers
Key FeaturesUnderstand the power, simplicity, and limitations of the core Selenium frameworkWrite clear, readable, and reliable tests that perform complex test automation tasksWork with ChromeDriver and GeckoDriver in headless modeBook Description
The second edition of Mastering Selenium 3.0 WebDriver starts by showing you how to build your own Selenium framework with Maven. You'll then look at how you can solve the difficult problems that you will undoubtedly come across as you start using Selenium in an enterprise environment and learn how to produce the right feedback when failing. Next, you’ll explore common exceptions that you will come across as you use Selenium, the root causes of these exceptions, and how to fix them. Along the way, you’ll use Advanced User Interactions APIs, running any JavaScript you need through Selenium; and learn how to quickly spin up a Selenium Grid using Docker containers. In the concluding chapters, you‘ll work through a series of scenarios that demonstrate how to extend Selenium to work with external libraries and applications so that you can be sure you are using the right tool for the job.
What you will learnProvide fast, useful feedback with screenshotsCreate extensible, well-composed page objectsUtilize ChromeDriver and GeckoDriver in headless modeLeverage the full power of Advanced User Interactions APIsUse JavascriptExecutor to execute JavaScript snippets in the browser through SeleniumBuild user interaction into your test script using JavascriptExecutorLearn the basics of working with AppiumWho this book is for
If you are a software tester or a developer with working experience in Selenium and competency with Java, who is interested in automation and are looking forward to taking the next step in their learning journey, then this is the book for you.
Mark Collin has been working in the software industry since 2001. He started his career in the financial sector before moving into consultancy. He has an eclectic range of skills and proficiencies, which include test automation, security and penetration testing, and performance testing. Mark is the creator and maintainer of driver-binary-downloader maven-plugin, and the Query library used in this book. He is also a core contributor to jmeter-maven-plugin, a tool that allows you to run JMeter tests through Maven. He has also contributed code to the core Selenium code base.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 431
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, 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.
Acquisition Editor: Shweta PantContent Development Editor: Onkar WaniTechnical Editor: Prajakta MhatreCopy Editor: Safis EditingProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Priyanka DhadkeProduction Coordinator: Shraddha Falebhai
First published: August 2015 Second edition: June 2018
Production reference: 1270618
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78829-967-1
www.packtpub.com
Mark Collin has been working in the software industry since 2001. He started his career in the financial sector before moving into consultancy. He has an eclectic range of skills and proficiencies, which include test automation, security and penetration testing, and performance testing. Mark is the creator and maintainer of driver-binary-downloader-maven-plugin, and the Query library used in this book. He is also a core contributor to jmeter-maven-plugin, a tool that allows you to run JMeter tests through Maven. He has also contributed code to the core Selenium code base.
Pinakin Chaubal is a B.E.(computer science) from Dharamsinh Desai Institute of Technology (affiliated with Gujarat University). He is a PMP certified professional and is certified at ISTQB foundation level. He has also done HP0-M47 QTP 11 certification. He has 17+ years of experience in the IT world and has been working with companies such as Patni, Accenture, and L&T Infotech. He is the creator of the Automation Geek channel on YouTube, which teaches about PMP, ISTQB, Selenium WebDriver (integration with Jenkins), page object model using Cucumber, and JavaScript (including ES6).
Nilesh Kulkarni is a staff software engineer, currently at PayPal. Nilesh has extensive experience of working with Selenium. Nilesh 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.
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.PacktPub.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.PacktPub.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.
Title Page
Copyright and Credits
Mastering Selenium WebDriver 3.0 Second Edition
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Packt Upsell
Why subscribe?
PacktPub.com
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Creating a Fast Feedback Loop
Making it easy for developers to run tests
Building our test project with Apache Maven
Running your tests in parallel
Parallel tests with TestNG
There are no silver bullets
Multiple browser support
Downloading WebDriver binaries automatically
Going headless
What happened to GhostDriver?
Summary
Producing the Right Feedback When Failing
Location, location, location
Tests are living documentation
Reliability
The test automation team that works in isolation
Oh, that test always flickers – don't worry about it
Baking in reliability
Git
Subversion
Continuous integration is key
Setting up TeamCity
Setting up Jenkins
Extending our capabilities by using a Selenium-Grid
A picture paints a thousand words
Don't be afraid of the big bad stack trace
Summary
Exceptions Are Actually Oracles
NoSuchElementException
NoSuchFrameException
NoSuchWindowException
ElementNotVisibleException
StaleElementReferenceException
InvalidElementStateException
UnsupportedCommandException
UnreachableBrowserException
SessionNotFoundException
WebDriverException – element is not clickable at point
NoAlertPresentException
Summary
The Waiting Game
Are we nearly ready yet?
I've timed it, and I know it takes 5 seconds for the page to load
Machine specification
Server specification
JavaScript engine performance
Networks
So, what do we do?
I just want Selenium to do it for me
Page load timeout
Script timeout
Implicitly wait timeout
It can slow my tests down?
It can break explicit waits?
The explicit wait that never finds an element
Hang on, I've tried this and it didn't work that way for me!
The explicit wait that works, but slows your tests down
The solution
Using explicit waits
Fluent waits, the core of explicit waits
Functions
Java8 lambdas
Summary
Working with Effective Page Objects
Why do you keep repeating yourself?
Starting out with page objects
Separation of concerns with page objects
Introducing the Java PageFactory class
Using PageFactory annotations
Initializing proxied objects
Problems with the Java PageFactory class
Introducing the Query object
So, which option should I use?
Creating extensible page objects
Turning your page objects into a readable DSL
Fluent page objects
Summary
Utilizing the Advanced User Interactions API
Getting started with the API
Using the API to solve difficult problems
Working with hover menus
Working with drag and drop
Working with offsets
Working with access keys
The Advanced Interactions API doesn't always work for me
Summary
JavaScript Execution with Selenium
Introducing the JavaScript executor
Let's not get carried away
So, what should we do with it?
A more complex example
Executing complex blocks of JavaScript with the JavascriptExecutor
Can I use JavaScript libraries?
Should I inject JavaScript libraries?
What about asynchronous scripts?
Building user interaction into your automation
Summary
Keeping It Real
File downloads with Selenium
The scenario
The problem
So, what's next?
Do you really need to download that file?
Checking that links are valid
What if I do need to download the file?
AutoIt
Java Robot class
Browser auto download
Extending our existing code
Downloading a file with the help of Selenium
But that's not the same as clicking on a link and downloading the file
Checking that the file we have downloaded is the correct one
You cannot track network traffic with Selenium
But I really want to track my network traffic!
Writing performance tests with Selenium
Penetration testing with Selenium
Summary
Hooking Docker into Selenium
Introducing Docker
Spinning up Selenium-Grid with Docker
Running tests against our new Selenium-Grid
Starting up Docker containers as part of the build
Using a Docker Maven plugin
Using Docker compose
What about the negatives?
Summary
Selenium – the Future
Machine learning — the new Holy Grail
Visual validation
Applitools Eyes
So what has this got to do with AI?
Self healing tests
Having your tests written for you
Summary
Appendix A: Contributing to Selenium
Selenium is amazing – how can I help make it better?
Getting set up to contribute to a Selenium repository
Aiding the documentation effort
Making changes to Selenium
Keeping your history clean
Now it's your turn
Appendix B: Working with JUnit
Switching from TestNG to JUnit
Summary
Appendix C: Introduction to Appium
Creating an Appium framework
Automating the Android calculator
Running the tests through Maven
Starting and stopping Appium with Maven
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book is going to focus on some of the more advanced aspects of Selenium. It will help you develop a greater understanding of Selenium as a test tool and provide you a series of strategies to help you create reliable and extensible test frameworks.
In the world of automation, there is rarely only one correct way of doing things. This book will provide you with a series of minimalistic implementations that are flexible enough to be customized to your specific needs.
This book is not going to teach you how to write bloated test frameworks that hide Selenium behind an impenetrable veil of obscurity. Instead, it will show you how to complement Selenium with useful additions that fit seamlessly into the rich and well-crafted API that Selenium already offers you.
If you are a software tester or a developer with working experience of Selenium and competency with Java who are interested in automation and are looking forward to taking the next step in your learning journey, then this is the book for you.
Chapter 1, Creating a Fast Feedback Loop, explains how to build a basic test framework that enables you to get started quickly. You will then focus on setting up a project using Maven to download your dependencies. Then you will learn about the advantages of running tests in parallel with multiple instances of the same browser in TestNG. Next, you will learn how to make your test code portable by automatically downloading the driver binaries using a Maven plugin and run your tests without interruption by running them in headless mode.
Chapter 2, Producing the Right Feedback When Failing, explores how to cope when tests start failing. This chapter gives you a good understanding of why reliability matters and how to configure your tests to run in a Maven profile. You will get an understanding of continuous integration, continuous delivery, and continuous deployment, and set up a test build in a continuous integration server. You also learn how to connect to Selenium-Grid, how to take screenshots of test failures, and investigate the causes of test failures by reading the stack trace.
Chapter 3, Exceptions Are Actually Oracles, provides a great deal of insight into what has gone wrong with your automated checks. You will explore the various exceptions generated by Selenium and understand what they mean. Further, you will gain a good understanding of how WebElement is a reference to an element in the DOM, understand the basic architecture of Selenium, and learn how it sends commands to the browser.
Chapter 4, The Waiting Game, explains the most common causes of test failures in automation and also various wait solutions in Selenium. You will explore how waits work in Selenium and how you should use them to ensure that you have stable and reliable tests.
Chapter 5, Working with Effective Page Objects, discusses page objects and explains how to use them effectively without letting them get out of control. It also teaches you how to use your page objects to reduce duplication, which in turn will help you make your code concise and your automated checks more readable. Then we will finish off the chapter by understanding how to build fluent page objects.
Chapter 6, Utilizing the Advanced User Interactions API, explains how to use the Advanced User Interactions API. You will learn how you can automate challenging scenarios such as hover menus and drag-and-drop controls. You will also explore some of the problems that you may come across when using the Advanced User Interactions API.
Chapter 7, JavaScript Execution with Selenium, helps you understand how to use the JavascriptExecutor class. This chapter explores how you can use it to work around complex automation problems. You also learn how to execute asynchronous scripts that use a callback to notify Selenium that they have completed the execution.
Chapter 8, Keeping It Real, shows you the limitations of Selenium. You then explore various scenarios that demonstrate how to extend Selenium to work with external libraries and applications so that you will be able to use the right tool for the job.
Chapter 9, Hooking Docker into Selenium, looks at how you can use Docker with Selenium. You will understand how easy it is to start spinning up your own grid in Docker. You will also look at how you can integrate Docker into your build process.
Chapter 10, Selenium - the Future, has a look at machine learning and artificial intelligence. You will then learn how to leverage some of that technology with Applitools EYES.
Appendix A, Contributing to Selenium, explores ways in which you can help the Selenium project.
Appendix B, Working with JUnit, explores the changes required to switch from TestNG to JUnit.
Appendix C, Introduction to Appium, explains how to create a basic Appium test framework.
The following software is required for the book:
Oracle JDK8
Maven 3
IntelliJ IDEA 2018
JMeter
Zed Attack Proxy
Docker
Mozilla Firefox
Google Chrome
Generally, the more the browsers you install, the better. You will be able to perform all the exercises in this book if you have at least Mozilla Firefox and Google Chrome installed.
The community edition of IntelliJ IDEA is free, but it's certainly worth purchasing a license to get access to the full functionality. You can use the older versions of IntelliJ IDEA or another IDE according to your preference. The code for this book has been written in IntelliJ IDEA 2018.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.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.packtpub.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/Mastering-Selenium-WebDriver-3.0-Second-Edition. 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!
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: "groupId should be a domain that you own/control and is entered in reverse."
A block of code is set as follows:
public class
BasicTest {
private
ExpectedCondition<Boolean>
pageTitleStartsWith
(
final
String searchString) {
return
driver -> driver.getTitle().toLowerCase(). startsWith(
searchString
.toLowerCase())
;
}
Any command-line input or output is written as follows:
mvn clean verify
-Dwebdriver.gecko.driver=<PATH_TO_GECKODRIVER_BINARY>
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: "Click on the Projects button on the top left."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.packtpub.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 packtpub.com.
One of the main problems you hear people talking about with Selenium is how long it takes to run all of their tests; I have heard figures ranging from a couple of hours to a couple of days. In this chapter, we will have a look at how we can speed things up and get the tests that you are writing to run both quickly and regularly.
Another problem that you may come across is getting other people to run your tests; this is usually because it is a pain to set up the project to work on their machine and it's too much effort for them. As well as making things run quickly, we are going to make it very easy for others to check out your code and get themselves up and running.
How does this create a fast feedback loop?
Well, first of all, allow me to explain what a fast feedback loop is. As developers change or refactor code, it's possible that they may make a mistake and break something. The feedback loop starts off when they commit code and is complete when they know whether their code changes have worked as expected, or something has been broken. We want to make this feedback loop as fast as possible, so ideally a developer will be running all of the tests that are available before every check in. They will then know whether the changes they made to the code have broken something before the code leaves their machine.
Eventually, we want to get to the point where developers are updating tests that fail because the functionality has changed as they go. The eventual code to turn the tests into living documentation, we will talk about a bit more about in Chapter 2, Producing the Right Feedback When Failing.
In this chapter, we are going to start by creating a basic test framework. What am I going to need? The software and browser versions used to write the code in this chapter are as follows:
Java SDK 8
Maven 3.5.3
Chrome 66
Firefox 60
It's a good idea to make sure that you atleast update to these versions to make sure everything works for you.
Ideally, we want our tests to run every time somebody pushes code to the central code repository; part of doing this is ensuring that it's very easy to run our tests. If somebody can just check out our code base and run one command and have all of the tests just work, it means they are far more likely to run them.
We are going to make this easy by using Apache Maven. To steal a quote from the Maven documentation:
Maven is a tool that can be used to build and manage Java projects (including downloading any dependencies that you require) and is used in many companies as part of the standard enterprise infrastructure. Maven is not the only solution to this problem (for example, Gradle is a very powerful alternative that is on par with Maven in many areas and exceeds it in a few), but it is one that you are most likely to see on the ground and one that most Java developers will have used at some point in their careers.
One of the major plus points is that it encourages developers to use a standardized project structure that makes it easy for people who know Maven to navigate around the source code; it also makes it very easy to plug into a CI system (such as Jenkins or TeamCity), as all the major ones understand Maven POM files.
How does this make it easy for developers to run tests? Well, when we have set our project up using Maven, they should be able to check out our test code and simply type mvn clean verify into a Terminal window. This will automatically download all dependencies, set up the class path, and run all of the tests.
It doesn't really get much easier than that.
Running your tests in parallel means different things to different people, as it can mean either of the following:
Run all of your tests against multiple browsers at the same time
Run your tests against multiple instances of the same browser
Should we run our tests in parallel to increase coverage?
I'm sure that when you are writing automated tests, to make sure things work with the website you are testing, you are initially told that your website has to work on all browsers. The reality is that this is just not true. There are many browsers out there and it's just not feasible to support everything. For example, will your AJAX-intensive site that has the odd flash object work in the Lynx browser?
The next thing you will hear is, "OK, well, we will support every browser supported by Selenium." Again, that's great, but we have problems. Something that most people don't realize is that the core Selenium teams official browser support is the current browser version, and the previous version at the time of release of a version of Selenium. In practice, it may well work on older browsers and the core team does a lot of work to try and make sure they don't break support for older browsers. However, if you want to run a series of tests on Internet Explorer 6, Internet Explorer 7, or even Internet Explorer 8, you are actually running tests against browsers that are not officially supported by Selenium.
We then come to our next set of problems. Internet Explorer is only supported on Windows machines, and you can have only one version of Internet Explorer installed on a Windows machine at a time.
Safari is only supported on OS X machines, and, again, you can have only one version installed at a time.
It soon becomes apparent that even if we do want to run all of our tests against every browser supported by Selenium, we are not going to be able to do it on one machine.
At this point, people tend to modify their test framework so that it can accept a list of browsers to run against. They write some code that detects, or specifies, which browsers are available on a machine. Once they have done this, they start running all of their tests over a few machines in parallel and end up with a matrix that looks like this:
This is great, but it doesn't get around the problem that there is always going to be one or two browsers you can't run against your local machine, so you will never get full cross-browser coverage. Using multiple different driver instances (potentially in multiple threads) to run against different browsers has given us slightly increased coverage. We still don't have full coverage though.
We also suffer some side effects by doing this. Different browsers run tests at different speeds because JavaScript engines in all browsers are not equal. We have probably drastically slowed down the process of checking that the code works before you push it to a source code repository.
Finally, by doing this we can make it much harder to diagnose issues. When a test fails, you now have to work out which browser it was running against, as well as why it failed. This may only take a minute of your time, but all those minutes do add up.
So, why don't we just run our tests against one type of browser for the moment. Let's make that test run against that browser nice and quickly, and then worry about cross-browser compatibility later.