Table of Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: Introduction to Selenium: Java Automation
Introduction
The Need for Testing Application
What Is Selenium?
Development and History of Selenium
The Genesis and Early Development (2004–2006)
The Birth of Selenium
Selenium Remote Control (RC)
Expanding Horizons (2006–2011)
Selenium IDE
The Introduction of WebDriver
Selenium 2.0: A Major Milestone
Maturing and Expanding (2011–2018)
The Advent of Selenium 3.0
Growth of the Selenium Ecosystem
The Modern Era of Selenium (2018–Present)
Selenium 4.0: The Future Realized
Why Selenium? Unraveling the Strengths of Selenium in Web Testing
Open Source Advantage
Language and Framework Flexibility
Cross-Browser and Cross-Platform Testing
Advanced Capabilities for Complex Test Scenarios
Community and Continuous Evolution
Selenium Architecture
Core Components
Automation Tool Comparison: Selenium and Alternatives
Java: Selenium’s Preferred Language
Summary
Chapter 2: Selenium Essentials: Setup and Browser Commands
Setting up Java on Your Machine
Step 1: Download the Java Development Kit (JDK)
Step 2: Install the JDK
Step 3: Set Environment Variables
Step 4: Verify the Installation
Step 5: Update When Necessary
Installing Eclipse IDE
Step 1: Download Eclipse
Step 2: Run the Eclipse Installer
Step 3: Install Eclipse
Step 4: Complete the Installation
Step 5: Launch Eclipse
Step 6: Configure Eclipse (Optional)
Step 7: Create a Java Project to Test
Selenium Installation
Step 1: Download Selenium WebDriver
Step 2: Create a New Java Project in Eclipse
Step 3: Add Selenium JARs to the Project
Step 4: Verify Installation
Step 5: Run the Test Script
Browser Commands
Opening a Selenium WebDriver Using Java Code
Opening a Web Page Online or Offline
Online Web Pages
Offline Web Pages
Understanding close and quit Commands
close Command
quit Command
Setting up Browser Size
Maximizing the Browser Window
Minimizing the Browser Window
Setting a Specific Browser Window Size
Using Full-screen Mode
Setting the Browser Position with Selenium WebDriver
Setting the Size Using Coordinates
Getting the Browser Position
Getting the Window Size
Navigating Through Web Pages with Selenium WebDriver
Navigating Back
Navigating Forward
Refreshing the Page
Summary
Chapter 3: Mouse and Keyboard Actions
Action Chains
Mouse Actions
Click
Double Click
Context Click
Click and Hold
Perform
Pause
Release
Reset
Mouse Movements
Move to Element
Move by Offset
Offset from Element
Offset from Viewport
Offset from Current Pointer Location
Drag and Drop on Element
Drag and Drop by Offset
Keyboard Actions
Keys
Key Down
Key Up
Send Keys
Scroll
Scroll to Element
Scroll by a Given Amount
Scroll from an Element by a Given Amount
Scroll from an Element with an Offset
Scroll from an Offset of Origin by Given Amount
Summary
Chapter 4: Web Elements
What Are Web Element Locators?
Why Are Web Element Locators Important in Web Automation?
Understanding the DOM
HTML and DOM Basics
HTML Web Elements
Attributes
Overview of the DOM Tree Structure
Relationships in the DOM
Locators
ID Locator
Name Locator
Link Text Locator
Partial Link Text Locator
Tag Name Locator
Class Name Locator
XPath Locators
Absolute XPath
Relative XPath
Attribute-Based XPath
Positional Filters in XPath
XPath with Logical Operators
Using and Operator
Using or Operator
Using the not Operator
CSS Selectors
Types of CSS Selectors and Their Use Cases
Basic Selectors
Type Selector
Class Selector
ID Selector
Universal Selector
Combinators
Descendant Selector (Space)
Child Selector (>)
Adjacent Sibling Selector (+)
General Sibling Selector (~)
Attribute Selectors
Presence
Exact Value
Partial Match Types
Contains (*=)
Begins with (^=)
Ends with ($=)
Specificity
Pseudo-Classes for Locating Elements
Locating the First Child Element
Locating the Last Child Element
Locating the Nth Element
Locating Multiple Web Elements
Table for Locators to Locate Multiple Elements
Common Challenges for Locating Web Elements
Best Practices to Overcome Challenges
Summary
Chapter 5: Navigations
Hyperlinks
Hyperlink by ID
Hyperlink by Text
Hyperlink by Partial Link Text
Hyperlink by XPath
nth Hyperlink
Return All Hyperlinks
Testing Hyperlinks
Check for a Valid Hyperlink
Check for Broken Images
Data Attributes Hyperlinks
Summary
Chapter 6: Buttons
Standard HTML Button
Asserting Button Type
Submit Button
Asserting Button Type
Image Button
Asserting Button Type
JavaScript Button
Disabled Button
Asserting Button Type
Toggle Button
Radio Buttons
Locating and Selecting with Radio Buttons
By ID
Using Label
By Index Values
Myth of Deselecting Radio Buttons
Validating Your Choices with Assertions
Validating / Confirming Element Type
Verifying the Selection State
Checkboxes
Locating and Selecting Checkboxes
By ID
Using Label
By Name
Selecting a Checkbox by Visible Text
Selecting a Checkbox by Value
Select All Checkboxes at Once
Selecting and Deselecting by Index
Deselecting a Checkbox by Visible Text
Deselecting a Checkbox by Value
Deselect All Checkboxes at Once
Validating a Checkbox with Assertions
Asserting Selection
Asserting Deselection
Asserting Element Type
SelectList
Locating and Interacting with SelectList
Locate and Select by Visible Text
Locate and Select by Value
Locate and Select by Index
Retrieving All Available Options
Get All Options
Deselecting Options in SelectList
Simulating Deselect by Selecting a Default Option
Validating SelectList Options and Selections
Assert the Selected Option
Assert Element Type
MultiSelectList
Selecting and Deselecting Options with MultiSelectList
Selecting Multiple Options
Deselecting Options
Validating Multiple Selections and Deselections
Asserting Multiple Selections:
Asserting Deselections
Asserting Element Type for MultiSelectList
Testing Considerations
Button Visibility and Accessibility
Button State
Button Functionality
Button Interaction
Validation Post-Interaction
Security Considerations
Performance Considerations
Cross-Platform and Cross-Browser Testing
Dynamic and Contextual Behavior
Error Handling
Summary
Chapter 7: iframes and Textboxes
iframes
Switching to an iframe
Switch Using ID
Switch Using Name
Switch Using Index Value
Hierarchy in Switching iframes
Navigating an iframe in a Hierarchy
Switch as an Element
Frames with Waits
Textboxes
Single Line Textbox
Multiline Textbox
Locating the Multiline
Inserting Values
Retrieving a Value from a Multiline Textbox
Summary
Chapter 8: Assertions
What Are Assertions?
The Need for Assertions
Hard Assertions (Asserts)
Soft Assertions (Verify)
Hard vs. Soft
Assert Methods in Selenium
Handling Assertion Failures
What Happens When an Assertion Fails?
Handling Assertion Failures Gracefully
Logging and Reporting Assertion Failures
Custom Assertions
Creating Custom Assertion Methods for Specific Application Requirements
Example: Custom Assertion for Checking Data Validity
Extending Assertion Functionality
Example: Extending Assertion Functionality in TestNG
Common Pitfalls and Mistakes in Selenium Assertions
Common Mistakes When Using Assertions
Avoiding False Positives and False Negatives
False Positives
False Negatives
Baseline Data
Environment Stability
Effective Reporting
Best Practices for Using Assertions in Selenium
When to Use Assertions
Keeping Assertions Simple and Specific
Using Meaningful Error Messages
Organizing Assertions within Test Cases
Summary
Chapter 9: Exceptions
What Is an Exception in Selenium?
Types of Exceptions
Common Exceptions in Selenium
Connection Exception
Element Interaction Exceptions
State-based Exceptions
Timeout and Delay Exceptions
Navigation Issues
Selector and Search Issues
JavaScript Execution Exceptions
Session Exceptions
Driver Configuration and Capability Exceptions
Input and Argument Exceptions
Alert and Pop-up Exceptions
Screenshot Exception
Movement and Action Exception
Browser Capability and Support Exception
Attribute and Property Exception
Cookie Handling Exception
Window Handling Exceptions
Element State Exceptions
Server and Response Exceptions
Other Exceptions
Handling Exceptions in Selenium
Why Exception Handling Is Essential in Selenium WebDriver
Handling Exceptions
Element Not Found Using try-catch
Timeout Exception Using try-catch-finally
Stale Element Exception Using try-catch-finally with throw
Handling Various Exceptions Using Multiple catch Blocks
Handling Custom Exceptions
Best Practices to Handle Exceptions
Summary
Chapter 10: Wait Strategies in Selenium Test Automation
Need for Waits
Dynamic Content Loading
Network Latency and Performance Variations
Synchronization
Reducing Flakiness
Uncertain User Input
Wait Types
Implicit Waits
Explicit Waits
Commonly Used ExpectedConditions in the Java Class
Fluent Waits
Key Features of a Fluent Wait
Selecting the Right Wait
Implicit Wait
Explicit Wait
Fluent Wait
Comparative Analysis of Implicit, Explicit, and Fluent Waits
Best Practices to Use Waits in Selenium Test Automation
Summary
Chapter 11: Page Object Model (POM)
The Conventional Approach
What Is POM?
Decoding DOM
Create a Page Class
Create Test Scripts Using Page Objects
Java Files in POM
Complete Analysis and Description of Creating a POM
Differences between Traditional and POM
POM Best Practices
Factory Page
Setting Up Page Factory
LoginPage.java: Representing the Login Page
DashboardPage.java: Representing the Dashboard Page
LoginTest.java: Test Script Utilizing Page Objects
Summarizing the Setup
Steps to Implement Page Factory
When to Use Page Factory
Differences Between POM and Page Factory
Best Practices for Implementing Page Factory
Limitations of POM and Page Factory
Limitations of POM
Limitations of Page Factory
When and Which One to Use: POM vs. Page Factory
When to Use POM
When to Use Page Factory
Making the Decision
Summary
Chapter 12: TestNG
Understanding Frameworks in Depth
JUnit Overview
Exploring the Features of JUnit
Transitioning to TestNG: Elevating Beyond JUnit
TestNG Features
Comparative Analysis: JUnit vs. TestNG
TestNG in Selenium WebDriver: A Synergistic Combination
Setting Up TestNG: A Step-by-Step Guide
Step 1: Installing TestNG in IDEs
Eclipse
IntelliJ IDEA
Step 2: Creating a New Java Project
Step 3: Incorporating TestNG into the Project
For Maven-based Projects
For non-Maven Projects
Step 4: Confirming Your TestNG Setup
TestNG Annotations and Attributes
@Test: The Core of TestNG
@Test with Other Annotations
@BeforeSuite and @AfterSuite
@BeforeTest/@AfterTest
@BeforeClass/@AfterClass
@BeforeMethod/@AfterMethod
TestNG Test Case with Selenium
HTML Snippet Example
Writing TestNG Test Case
TestNG Assertions
Parameterized Testing in TestNG
Implementing Parameterized Testing in TestNG
Step 1: Define a DataProvider
Step 2: Create a Test Method Using DataProvider
Advanced TestNG Configuration and Parallel Execution
Utilizing testng.xml for Test Execution
Enabling Parallel Execution in testng.xml
Implementing Parallel Execution: A Practical Example
Best Practices for Using TestNG with Selenium
Summary
Index
Master the art of automated testing using Selenium with Java in this comprehensive guide. Whether you're a beginner or an experienced tester, the book equips you with the knowledge and techniques to build robust and maintainable test suites, ensuring the quality and reliability of your web applications.
This book starts introducing the basics of automated testing and the importance of Selenium. It then covers the setup and configuration of the Selenium WebDriver in Java, providing a solid foundation for your testing environment. You'll learn essential aspects of Selenium testing in Java, including working with different browsers, locating web elements using locators, and performing actions on them. From there, you’ll explore how to handle dynamic web pages and effective wait mechanisms and verifications to ensure accurate and reliable test results. The book also guides you in setting up Selenium in Java for continuous integration and emphasizes best practices for test codeorganization and maintainability, such as the Page Object Model (POM) and structuring test suites effectively. By the end, you’ll have the expertise to address advanced scenarios, such as working with iframes, and know how TestNG enhances Selenium automation, enabling structured tests, data-driven insights, and swift parallel executions.
Throughout the book, you'll benefit from real-world examples and practical exercises that reinforce the concepts. The clear explanations and step-by-step guidance make it easy to follow along and apply the knowledge to your own testing projects.
Understand the fundamentals of automated testing and the role of Selenium in web application testing
Set up the Selenium WebDriver in Java and configure the testing environment
Work with different web browsers and their drivers to perform cross-browser testing
Identify and locate web elements using various locators, such as IDs, class names, CSS selectors, and XPath expressions
Perform actions on web elements, such as clicking buttons, entering text, submitting forms, and navigating through web pages
Handle dynamic pages by implementing effective wait mechanisms, including implicit waits, explicit waits, and fluent waits
Verify and assert expected conditions and outcomes using assertions and verification techniques provided by Selenium in Java
Apply best practices for test code organization and maintainability, including using the Page Object Model (POM) design pattern
Handle advanced scenarios, such as working with iframes, and elevating Selenium automation through TestNG’s structured frameworks, data utilization, and parallel processing
Software testers, quality assurance professionals, and developers interested in mastering automated testing with Selenium and Java. Suitable for various experience levels. Offers practical insights and techniques to automate web application testing accurately and reliably. Benefits testers, developers, and individuals familiar with Java and web testing, empowering them to write robust, maintainable test code and integrate Selenium seamlessly into their workflows.