0% found this document useful (0 votes)
12 views58 pages

Software Testing

The document provides a comprehensive overview of software testing, emphasizing its importance in ensuring software quality and reliability through various methods and types, including manual and automated testing. It details automation testing, particularly using Selenium, including its components, installation, and script creation for web automation. Additionally, it covers handling drop-downs in web applications using Selenium with Java, highlighting the necessary prerequisites and dependencies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views58 pages

Software Testing

The document provides a comprehensive overview of software testing, emphasizing its importance in ensuring software quality and reliability through various methods and types, including manual and automated testing. It details automation testing, particularly using Selenium, including its components, installation, and script creation for web automation. Additionally, it covers handling drop-downs in web applications using Selenium with Java, highlighting the necessary prerequisites and dependencies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

UNIT-1
Software testing:
Software testing is the process of evaluating and verifying that a software
product or application functions correctly, securely, and efficiently according to
its specific requirements. It involves assessing the functionality of a software
program to identify errors, gaps, and discrepancies between expected and
actual outcomes before the software is deployed or goes live.

Key aspects of software testing include:


Objective:
To find issues and defects (bugs) early in the development lifecycle to
minimize risks and ensure high-quality software delivery.
Methods:
It can be performed manually by human testers or through automation using
tools and scripts.
Approaches:
White Box Testing: Focuses on the internal structure and logic of the code.
Black Box Testing: Evaluates the software's functionality without examining
the internal code.
Grey Box Testing: Combines elements of both white and black box testing.
Types:
Functional Testing: Assesses specific functions and features.
Non-Functional Testing: Evaluates aspects like performance, security,
usability, and reliability.
Stages:
Unit Testing: Testing individual components or units of code.
Integration Testing: Testing how different parts of the application work
together.
System Testing: Testing the complete and integrated software system.
Acceptance Testing: Verifying that the software meets user requirements and
is ready for deployment.

1|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Software testing is a crucial part of the software development lifecycle,


ensuring that the final product is reliable, meets user expectations, and is free
of critical defects.
Automation testing
Automation testing, also known as automated software testing or test
automation, is a software testing technique that utilizes specialized tools and
scripts to automatically execute test cases on software applications. This
approach aims to reduce or eliminate the need for manual intervention in
repetitive and time-consuming testing tasks, such as regression testing.

Key aspects of automation testing include:


Scripted Execution:
Test cases are converted into scripts that can be automatically executed by
testing tools. These scripts can simulate user interactions, input data, and
verify expected outcomes.
Efficiency and Speed:
Automation significantly accelerates the testing process, allowing for faster
feedback on software quality and enabling more frequent test runs.
Improved Accuracy and Consistency:
Automated tests reduce the potential for human error and ensure consistent
execution across multiple test runs and environments.
Increased Test Coverage:
Automation allows for the execution of a larger volume of test cases, leading
to broader test coverage and the detection of more defects.
Integration with CI/CD:
Automation testing integrates seamlessly with Continuous Integration and
Continuous Delivery (CI/CD) pipelines, enabling continuous code verification
and faster deployments.
Focus on High-Value Tasks:
By automating repetitive tasks, testers can dedicate more time to exploratory
testing, test case design, and other high-value activities
Common types of tests suitable for automation include:
Regression testing:

2|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

To ensure that new code changes do not negatively impact existing


functionality.
Unit testing:
To validate individual components or units of code.
API testing:
To test the functionality and performance of Application Programming
Interfaces.
Performance testing:
To assess the application's responsiveness and stability under various loads.
While automation testing offers numerous benefits, it requires initial
investment in tool selection, script development, and maintenance. It is not
suitable for all testing scenarios, particularly those requiring human judgment
and creativity, such as exploratory testing.
Selenium and its Components:
Selenium is an open-source suite of tools designed for automating web
browsers. It is primarily used for functional and cross-browser testing of web
applications, enabling the simulation of user interactions and validation of
website functionality across various browsers and operating systems.

The core components of the Selenium suite are:


Selenium IDE (Integrated Development Environment):
A Firefox and Chrome add-on that allows for recording and replaying user
interactions with web pages. It provides a simple way to create and execute
automated tests without requiring extensive programming knowledge.
Selenium WebDriver:
The central and most widely used component of Selenium. WebDriver
provides a programming interface for interacting with web browsers
directly. It allows testers to write automated test scripts in various
programming languages (e.g., Java, Python, C#, JavaScript) to control
browser actions, interact with web elements, and perform validations.
Selenium Grid:
A tool that enables parallel execution of tests across multiple machines and
browsers simultaneously. It uses a hub-and-node architecture to distribute

3|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

tests, significantly reducing the time required for large test suites and
facilitating scalable test automation.
Selenium RC (Remote Control):
An older component of Selenium, now largely superseded by WebDriver. RC
allowed testers to write test scripts in various languages and then execute
them by sending commands to a Selenium RC server, which in turn
controlled the browser. While still functional, WebDriver offers more direct
and efficient browser interaction.

Selenium IDE features:

Selenium IDE offers a range of features designed to simplify the creation and
execution of automated web tests:
Record and Playback:
This core feature allows users to record their interactions with a web
application and then play them back as automated test scripts. This
eliminates the need for manual coding in many cases.
Exporting Test Cases:
Tests recorded in Selenium IDE can be exported to various programming
languages, including Java, Python, Ruby, and C#, enabling integration with
more complex testing frameworks or custom automation scripts.
Intelligent Field Selection and Multiple Locators:
Selenium IDE automatically identifies and records multiple locators (e.g., ID,
name, XPath, CSS selector) for each element interacted with during
recording, making tests more resilient to minor UI changes.
Control Flow Statements:
It includes commands for adding conditional logic (e.g., if, else if, else) and
looping structures (e.g., while, times), allowing for more sophisticated test
scenarios.
Debugging Capabilities:
Features like setting breakpoints, stepping through commands, and pausing
on exceptions aid in identifying and resolving issues within test scripts.
Parallel Execution:

4|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

With the Selenium command-line runner, tests created in Selenium IDE can
be executed in parallel across multiple browsers and operating systems,
including on a Selenium Grid.
Plugin Support:
Selenium IDE's functionality can be extended through the use of plugins,
allowing for integration with third-party services or custom commands.
Test Suite Management:
It provides features for organizing multiple test cases into test suites,
facilitating the execution of related tests together.
Automatic Waiting:
The IDE automatically waits for page loading and element presence,
reducing the need for explicit wait commands in test scripts.
User-Friendly Interface:
With its intuitive record-and-playback mechanism and visual editor, Selenium
IDE is accessible to users with varying levels of programming experience.

Selenium Download and Installation


Selenium download and installation involves setting up the necessary
components to use Selenium for web automation. The process typically
includes:
Installing a Programming Language and IDE (if applicable):
Selenium supports various languages like Java, Python, C#, Ruby, etc. Install
the desired language's runtime environment.
If using an IDE like Eclipse for Java, install and configure it.
Downloading Selenium Client Libraries:
Visit the official Selenium website's downloads page (selenium.dev/downloads).
Download the client library for the chosen programming language
(e.g., selenium-java.zip for Java, pip install selenium for Python).
Downloading Browser Drivers:
Selenium interacts with browsers through specific drivers (e.g., ChromeDriver
for Chrome, GeckoDriver for Firefox, MSEdgeDriver for Edge).
Download the appropriate driver for the target browser and ensure its version is
compatible with the browser installed on the system.

5|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Place the downloaded driver executable in a location accessible by the


system's PATH environment variable, or specify its path in the automation
script.
Configuring the Project/Environment:
For Java: Extract the downloaded Selenium client library ZIP and add the JAR
files (including those in the lib folder) to the project's build path in the IDE.
For Python: The pip install selenium command handles most of the setup.
For other languages: Refer to the specific language's documentation for
integrating the Selenium library.
Verifying the Installation:
Write a simple test script to launch a browser and navigate to a website to
confirm that Selenium and the browser driver are correctly configured and
working.
This process enables the use of Selenium WebDriver to automate browser
interactions for testing or other web automation tasks.

Installation of Firebug for use with Selenium:


Open Firefox and navigate to the Add-ons page: Access the Firefox menu
(usually three horizontal lines or a gear icon) and select "Add-ons and themes" or
"Add-ons."
Search for Firebug: In the search bar on the Add-ons page, type "Firebug" and
press Enter.
Add Firebug to Firefox: Locate the Firebug extension in the search results and
click the "Add to Firefox" button next to it.
Complete the installation: Follow any prompts that appear, which may include
restarting the browser.
Verify installation: After restarting (if necessary), you should see the Firebug
icon in your Firefox toolbar or menu. Click it to open the Firebug interface and
confirm it's working.
Creating Selenium Scripts using Firebug:
Firebug is primarily used to identify and verify locators (like XPath or CSS
selectors) for web elements, which are then used in your Selenium scripts.
Open Firebug:
Launch Firebug in your Firefox browser by clicking its icon or pressing F12.

6|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Inspect elements:
Navigate to the web page you want to automate. Use the "Inspect" tool
within Firebug (often represented by a cursor icon) to hover over and select
the specific web element you need to interact with in your script.
Copy locator:
Once an element is selected in Firebug, its HTML structure will be
displayed. Right-click on the relevant HTML node and choose options like
"Copy XPath" or "Copy CSS Selector" to obtain the locator for that element.
Incorporate into Selenium script:
Use the copied locator in your Selenium WebDriver script to find and interact
with the element.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MySeleniumScript {


public static void main(String[] args) {
// Set path to your GeckoDriver executable
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");

WebDriver driver = new FirefoxDriver();


driver.get("https://example.com"); // Replace with your URL

// Use the XPath copied from Firebug

driver.findElement(By.xpath("//input[@id='username']")).sendKeys("myuserna
me");

// Further actions on the element


// driver.findElement(By.xpath("//button[@id='loginButton']")).click();

driver.quit();
}
}

7|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Selenium WebDriver utilizes various locator strategies to identify and interact


with web elements on a page. These locators enable test automation scripts
to pinpoint specific elements within the Document Object Model (DOM).

The primary locator types in Selenium are:


ID:
Locates elements based on their unique id attribute. This is generally the
fastest and most reliable method when an id is available and unique.
Name:
Locates elements based on their name attribute. While often used for form
elements, the name attribute may not always be unique on a page.
Class Name:
Locates elements based on their class attribute. This can return multiple
elements if several elements share the same class name.
Tag Name:
Locates elements based on their HTML tag name, such as div, input, a, etc.
This also typically returns multiple elements.
Link Text:
Specifically for anchor (<a>) elements, it locates the element based on the
exact visible text of the link.
Partial Link Text:
Also for anchor (<a>) elements, it locates the element based on a partial
match of the visible text of the link.
CSS Selector:
A powerful and flexible method that uses CSS selectors to locate
elements. It can target elements based on various attributes, relationships,
and styles.
XPath:
A robust query language for navigating through XML documents (including
HTML). XPath offers highly precise targeting of elements, including those
without unique IDs or names, and can traverse the DOM in various directions
(parent, child, sibling, etc.). It can be absolute (starting from the root) or
relative (starting from a specific point).

8|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

UNIT-2
Selenium WebDriver Installation with Eclipse
Installing Selenium WebDriver with Eclipse involves several key steps to
set up your development environment for web automation using Java.

1. Prerequisites:
 Java Development Kit (JDK):
Ensure a compatible JDK version (e.g., Java 8 or higher) is installed on
your system.
 Eclipse IDE for Java Developers:
Download and install the appropriate Eclipse IDE version for Java
development.
2. Download Selenium WebDriver Libraries:
 Navigate to the official Selenium website and download the latest stable
version of the "Selenium Client & WebDriver Language Bindings" for
Java. This will typically be a ZIP file containing the necessary JAR files.
 Extract the contents of the downloaded ZIP file to a chosen location on
your system.
3. Configure Selenium in Eclipse:
 Create a Java Project:
Launch Eclipse and create a new Java project (File > New > Java
Project). Provide a suitable project name and click Finish.
 Add External JARs to Build Path:
 Right-click on your newly created project in the Package Explorer and
select "Properties."
 In the Properties window, navigate to "Java Build Path" and select the
"Libraries" tab.
 Click on "Add External JARs..."
 Browse to the location where you extracted the Selenium WebDriver ZIP
file. Select all the JAR files within the main extracted folder and also all
the JAR files within the lib subfolder.
 Click "Open" to add them to your project's build path.

9|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Click "Apply and Close" to save the changes.


4. Download Browser Driver:
 Download the specific browser driver (e.g., ChromeDriver for Chrome,
GeckoDriver for Firefox) that matches the browser version you intend to
automate.
 Place the downloaded executable driver file (e.g., chromedriver.exe) in a
location accessible by your project, or set its path as a system property in
your code.
5. Verify Installation:
 Create a new Java class within your project.
 Write a simple Selenium script to verify the setup (e.g., launching a browser
and navigating to a URL). If no compilation errors occur and the script
executes successfully, your Selenium WebDriver installation with Eclipse is
complete.

Selenium Handling Drop-Downs using Java


Selenium is a powerful tool for web automation and testing, and one of
its core components is the WebDriver. When working with web
applications, handling drop-down menus is a common requirement. In
this guide, we’ll explore how to handle drop-downs using Selenium with
Java. Drop-downs are key elements in many web forms, and mastering
their manipulation is crucial for effective test automation.
Whether you’re selecting options by visible text, index, or value,
Selenium’s Select class provides the functionality you need to automate
these interactions seamlessly.
Prerequisite
We will be required 3 main things:
1. Java Development Kit (JDK) installed.
2. Browser Driver (e.g., ChromeDriver for Chrome).
3. IDE like Eclipse or IntelliJ IDEA.
Dependencies Selenium Handling Drop-Downs using Java
We will be required to have dependencies for selenium and for that, we
will add dependencies in pom.xml
pom.xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>

10 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

<artifactId>selenium-java</artifactId>
<version>4.21.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-support</artifactId>
<version>4.21.0</version>
</dependency>
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Drop-Down Test</title>
</head>
<body>
<h1>Drop-Down Test Page</h1>
<form>
<label for="dropdownId">Select an option:</label>
<select id="dropdownId" name="options">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</form>
</body>
</html>
Application.java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class Application {


public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "chromeDriverPath");

// Initialize WebDriver
WebDriver driver = new ChromeDriver();

11 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

// Navigate to the desired webpage


driver.get("http://127.0.0.1:5500/htmlfile.html");

// Locate the drop-down element


WebElement dropdownElement =
driver.findElement(By.id("dropdownId"));

// Create an instance of Select class


Select dropdown = new Select(dropdownElement);

// Select option by visible text


dropdown.selectByVisibleText("Option 2");

// Select option by index


dropdown.selectByIndex(2); // Selects the second option (index starts
from 0)

// Select option by value


dropdown.selectByValue("option2");

// Get the selected option


WebElement selectedOption = dropdown.getFirstSelectedOption();
System.out.println("Selected option: " + selectedOption.getText());

// Close the browser


//driver.quit();
}
}
Explicit and Implicit Wait

In Selenium with Java, "waits" are crucial for handling dynamic web
elements and ensuring test stability. Two primary types of waits are implicit
and explicit waits.

Implicit Wait:
 Global Setting: An implicit wait sets a default timeout for the entire
WebDriver instance. This means that if an element is not immediately
found, the driver will poll the DOM for the specified duration before throwing
a NoSuchElementException.
 Syntax:
12 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Java
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); //
Waits for up to 10 seconds
 Behavior: Applies to all findElement and findElements calls. If the element
appears before the timeout, the script proceeds immediately. If not, it waits
for the full duration.
Explicit Wait:
 Specific Condition: An explicit wait is used to wait for a specific condition
to be met before proceeding. This wait is applied to a particular element or
condition, not globally.
 Syntax:
Java
WebDriverWait wait = new WebDriverWait(driver,
Duration.ofSeconds(10)); // Maximum wait time
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someElem
entId")));
 ExpectedConditions:
ExpectedConditions provides a variety of conditions to wait for, such
as elementToBeClickable, visibilityOfElementLocated, textToBePresentIn
Element, etc.
 Behavior:
The script pauses until the specified condition is true or the maximum
timeout is reached. If the condition is met before the timeout, the script
continues. If not, a TimeoutException is thrown.
Key Differences:
 Scope: Implicit wait is global; explicit wait is element/condition-specific.
 Flexibility: Explicit wait offers more granular control over waiting
conditions.
 Recommendation: It is generally recommended not to mix implicit and
explicit waits as this can lead to unpredictable and longer-than-expected
wait times. Prioritize explicit waits for specific, dynamic elements and use
implicit waits only if a general, global timeout is truly necessary.
Handling alerts and pop-ups in Selenium

13 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Handling alerts and pop-ups in Selenium WebDriver with Java involves


using the Alert interface and the switchTo() method.

1. Switching to the Alert:


Before interacting with an alert, Selenium's focus must be shifted from the
main web page to the alert window. This is achieved using:
Java
Alert alert = driver.switchTo().alert();

2. Interacting with the Alert:


Once switched to the alert, various actions can be performed using
the Alert object:
 Accepting the alert (clicking "OK" or "Yes"):
Java
alert.accept();
 Dismissing the alert (clicking "Cancel" or "No"):
Java
alert.dismiss();
Retrieving the text from the alert.
Java
String alertText = alert.getText();
 Sending text to a prompt alert (entering input):
Java
alert.sendKeys("Your input text here");

3. Handling Unexpected Alerts:


For unexpected alerts that may appear at unpredictable
times, WebDriverWait with ExpectedConditions.alertIsPresent() can be
used to wait for the alert and then handle it within a try-catch block to
prevent UnhandledAlertException.
Java
try {
WebDriverWait wait = new WebDriverWait(driver,
Duration.ofSeconds(10));

14 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

wait.until(ExpectedConditions.alertIsPresent());
Alert unexpectedAlert = driver.switchTo().alert();
// Perform actions on the unexpected alert (e.g., accept, dismiss, log
text)
unexpectedAlert.accept();
} catch (NoAlertPresentException e) {
System.out.println("No unexpected alert found.");
}

4. Handling Browser Pop-up Windows:


For new browser windows or tabs that open (not JavaScript alerts),
Selenium uses window handles to switch between them:
Java
// Get the handle of the current window
String originalWindow = driver.getWindowHandle();

// Perform an action that opens a new window/tab


// ...

// Get all window handles


Set<String> allWindowHandles = driver.getWindowHandles();

// Switch to the new window/tab


for (String handle : allWindowHandles) {
if (!handle.equals(originalWindow)) {
driver.switchTo().window(handle);
break;
}
}

// Perform actions in the new window/tab


// ...

// Switch back to the original window


driver.switchTo().window(originalWindow);
handling web tables in selenium

15 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Handling web tables in Selenium involves locating the table, then iterating
through its rows and columns to extract or interact with data. This process
applies to both static and dynamic tables, though dynamic tables may
require more robust element location strategies.

Steps to handle web tables in Selenium:


 Locate the Web Table: Identify the <table> element using a suitable
locator like ID, class name, or XPath.
Java
WebElement table = driver.findElement(By.id("exampleTable"));
 Get All Rows: Find all <tr> elements within the located table.
Java
List<WebElement> rows = table.findElements(By.tagName("tr"));
 Iterate Through Rows and Cells:
o Loop through each <tr> element (row).
o Inside the row loop, find all <td> (data cell) or <th> (header cell) elements
within that specific row.
o Extract the text or perform actions on individual cells.
Java
for (WebElement row : rows) {
List<WebElement> cells = row.findElements(By.tagName("td")); // Or
By.tagName("th") for headers
for (WebElement cell : cells) {
System.out.print(cell.getText() + " ");
}
System.out.println();
}
 Handling Header Rows (Optional): If the table has a header row, you can
skip it in your iteration by starting the row loop from the second element
(index 1).
Java
for (int i = 1; i < rows.size(); i++) {
WebElement row = rows.get(i);
// ... process cells as above
}

Additional Considerations:
16 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Dynamic Tables:
If the table content changes dynamically, ensure your locators are robust
enough to handle these changes. You might need to use more flexible
XPaths or wait conditions.
 Specific Cell Access:
To access a specific cell, you can combine the row and column index
within your iteration or construct a precise XPath.
 Actions on Cells:
You can perform various actions on cells, such as clicking on links within
cells, entering text into input fields, or verifying data.
frames in selenium

In Selenium, "frames" (including the more common "iframes" or "inline


frames") refer to elements on a web page that embed another HTML
document within the parent HTML document. Essentially, they create a
separate, self-contained browsing context within the main web page.

Here's a breakdown:
 Purpose:
Frames are used to embed content from another source, such as videos,
advertisements, or even entire external web pages, within the current
page without requiring a full page reload.
 Isolation:
The content within a frame operates independently from the main
document. This means that elements inside a frame are not directly
accessible by Selenium WebDriver unless the driver's focus is explicitly
switched to that frame.
 Handling in Selenium:
To interact with elements located inside a frame, Selenium WebDriver's
focus must be switched to that specific frame using
the driver.switchTo().frame() method. This method can accept:
 Index: The numerical index of the frame (starting from 0).
 Name or ID: The name or id attribute of the frame element.
 WebElement: The WebElement object representing the frame itself.
Switching Back:
17 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

After interacting with elements within a frame, it is crucial to switch the


driver's focus back to the main document
using driver.switchTo().defaultContent() or to the parent frame
using driver.switchTo().parentFrame() if dealing with nested
frames. Selenium cannot directly switch between frames; it must return to
the main document first.
Dynamic Elements

Dynamic web elements in Selenium refer to components on a web page


whose properties, such as ID, class, text, or position, change during
runtime. These changes can occur due to user interactions, page reloads,
AJAX requests, or other client-side scripts, making them challenging to
locate and interact with using static locators.

Common scenarios for dynamic elements include:


 Dynamically generated IDs or class names:
Attributes like id or class might change with each page load or user
interaction.
 Elements loaded asynchronously:
Content might appear or disappear on the page after the initial page load,
often through AJAX calls.
 Dynamic tables or lists:
The number of rows, columns, or items within a table or list might change
based on data or user filters.
 Pop-ups or alerts:
These elements might appear or disappear based on specific actions or
conditions.
Strategies for handling dynamic elements in Selenium:
 Waits:
 Implicit Waits: Set a global timeout for Selenium to wait for elements to
appear before throwing a NoSuchElementException.
 Explicit Waits: Use WebDriverWait and ExpectedConditions to wait for
specific conditions to be met, such as element visibility, clickability, or
presence. This is generally preferred for handling dynamic elements as it
allows for more precise control.

18 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Robust Locators:
 Dynamic XPath and CSS Selectors: Use XPath functions
like contains(), starts-with(), or ends-with() to locate elements based on
partial or consistent parts of their attributes. CSS selectors can also be
combined to target elements effectively.
 Relative Locators: Selenium 4 introduces relative locators
(e.g., above(), below(), toLeftOf(), toRightOf(), near()) which can be useful
when elements don't have stable attributes but their position relative to
other elements is consistent.
JavaScript Executor:
 Execute JavaScript directly to interact with elements or retrieve their
properties when Selenium's built-in methods are insufficient.
Actions Class:
 Handle complex interactions like drag-and-drop, hover, or keyboard
actions that might be necessary for interacting with certain dynamic
elements.
Handling Alerts and Frames:
 Use driver.switchTo().alert() for pop-up alerts
and driver.switchTo().frame() for elements within iframes.

robot api in selenium

The term "Robot API in Selenium" can refer to two distinct concepts:
 Robot Framework's SeleniumLibrary:
This is the most common interpretation. Robot Framework is a generic,
open-source test automation framework that uses a keyword-driven
approach. It integrates with various external libraries, and one of the most
prominent for web testing is the SeleniumLibrary. This library provides a
set of high-level keywords that abstract the underlying Selenium
WebDriver API, making it easier to write web automation tests without
extensive programming knowledge. For example, instead of
writing driver.findElement(By.id("username")).sendKeys("test"), you would
use a keyword like Input Text username_field test.
 Java's java.awt.Robot Class with Selenium:
In Java-based Selenium projects, the java.awt.Robot class can be used to
simulate native system input events, such as keyboard presses and
19 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

mouse movements. This is particularly useful for handling scenarios that


Selenium WebDriver cannot directly manage, such as:
 File uploads: Interacting with native file dialogs to select and upload files.
 System-level pop-ups: Handling operating system-level alerts or
notifications that appear outside the browser context.
 Desktop interactions: Automating actions on desktop applications or
elements that are not part of the web page.
While Selenium WebDriver focuses on browser automation,
the Robot class provides a way to interact with the operating system,
bridging the gap between web and desktop automation within a Java-based
Selenium project.
In summary, when discussing "Robot API in Selenium," it is crucial to clarify
whether the reference is to the Robot Framework's SeleniumLibrary for
simplified web testing or the Java Robot class for handling native system
interactions alongside Selenium WebDriver.
autoit selenium

AutoIt is a freeware BASIC-like scripting language designed for automating


the Windows GUI and general scripting, commonly used in conjunction with
Selenium WebDriver to handle desktop-level interactions that Selenium
cannot directly manage.

Purpose in Selenium Automation:


Selenium WebDriver is primarily designed for browser automation and
cannot directly interact with native Windows elements like file upload
dialogs, system pop-ups, or other desktop applications. AutoIt bridges this
gap by providing functionalities to automate these interactions.

How AutoIt is used with Selenium:


 Develop AutoIt Scripts:
AutoIt scripts are written to automate specific desktop interactions (e.g.,
selecting a file in a file upload dialog, clicking a button in a Windows pop-
up). These scripts are saved with a .au3 extension.
 Compile AutoIt Scripts:
The .au3 scripts are then compiled into executable .exe files using the
AutoIt compiler.

20 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Integrate into Selenium:


In the Selenium automation script (e.g., written in Java, Python, C#), the
compiled AutoIt .exe file is called using a command-line execution method
(e.g., Runtime.getRuntime().exec() in Java, subprocess.call() in Python).
 Execute and Resume Selenium:
The Selenium script triggers the AutoIt executable at the point where a
desktop interaction is required. After AutoIt completes its task, the
Selenium script resumes control to continue with browser-based
automation.
Common Use Cases:
 File Uploads:
Handling the Windows file dialog box that appears when uploading files to
a web application.
 Downloading Files:
Interacting with download prompts and saving files to a specific location
on the system.
 Windows Authentication Pop-ups:
Automating login credentials in basic authentication pop-ups.
 Handling System Dialogs:
Interacting with various other system-level pop-ups or dialog boxes that
might appear during test execution.

21 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

UNIT-3
Test Automation Framework

A Selenium framework refers to a structured collection of tools, libraries, and


design patterns used with Selenium to build efficient, maintainable, and
scalable automated web testing solutions. Selenium itself is an open-source
umbrella project for various tools and libraries designed for browser
automation, primarily used for functional and cross-browser testing of web
applications.

Key aspects and components of a Selenium framework include:


 Selenium WebDriver:
This is the core component, providing language-specific bindings (e.g., Java,
Python, C#, JavaScript) to interact with and control web browsers. It allows
simulating user actions like clicking, typing, navigating, and asserting
element states.
 Test Framework Integration:
Selenium frameworks often integrate with popular testing frameworks like
TestNG or JUnit (for Java), Pytest or Unittest (for Python), or Mocha/Jasmine
(for JavaScript) to manage test execution, reporting, and assertions.
 Page Object Model (POM):
A common design pattern in Selenium frameworks, POM promotes code
reusability and maintainability by representing web pages as classes, with
elements and interactions defined within those classes. This separates test
logic from page element locators.
 Data-Driven Testing:
Frameworks can be designed to support data-driven testing, where test data
is stored externally (e.g., in Excel, CSV, or databases) and fed into test
scripts, enabling the execution of the same test logic with different data sets.
 Keyword-Driven Testing:
This approach focuses on defining keywords or actions that represent
specific operations (e.g., "login," "clickButton"), allowing non-technical users
to create test cases using these keywords.
 Hybrid Frameworks:

22 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Many real-world Selenium frameworks combine elements of data-driven and


keyword-driven approaches, offering flexibility and robustness.
 Reporting and Logging:
Frameworks typically include mechanisms for generating test reports (e.g.,
HTML reports, Extent Reports) and logging test execution details for analysis
and debugging.
 Version Control Integration:
Integration with version control systems like Git is crucial for managing test
code and facilitating collaboration among team members.
 Continuous Integration/Continuous Delivery (CI/CD) Integration:
Selenium frameworks are often integrated into CI/CD pipelines to enable
automated testing as part of the software delivery process, ensuring
continuous quality assurance.

BENEFITS OF automation framework in selenium

An automation framework in Selenium provides a structured and organized


approach to test automation, offering numerous benefits:
 Improved Maintainability:
Frameworks promote modularity and reusability of test scripts, making them
easier to maintain and update when application changes occur. This reduces
the effort and cost associated with test script maintenance.
 Enhanced Reusability:
Common functionalities, such as page object models, utility functions, and
test data management, can be encapsulated within the framework and
reused across multiple test cases, minimizing code duplication.
 Increased Efficiency and Reduced Time-to-Market:
Automation frameworks streamline the test creation and execution process,
allowing for faster test cycles and quicker releases of software.
 Better Organization and Readability:

23 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Frameworks provide a clear structure for organizing test cases, test data,
and reports, improving the readability and understanding of the automation
suite for all team members.
 Facilitated Collaboration:
A well-defined framework makes it easier for multiple testers to contribute to
the automation effort, as it enforces consistent coding standards and
practices.
 Scalability and Parallel Execution:
Frameworks can be designed to support parallel test execution across
multiple browsers and environments, significantly reducing the overall test
execution time for large test suites.
 Robust Reporting and Analysis:
Frameworks often integrate with reporting tools, providing detailed test
results, logs, and screenshots, which aid in identifying and debugging issues
more effectively.
 Reduced Manual Effort and Human Error:
Automating repetitive tasks minimizes the need for manual intervention,
leading to fewer errors and more reliable test results.
 Early Defect Detection:
By enabling continuous and frequent testing, automation frameworks help
identify defects early in the development cycle, reducing the cost and effort
of fixing them later.
 Cost-Effectiveness:
While initial setup may require an investment, the long-term benefits of
reduced maintenance, faster releases, and improved quality lead to a higher
return on investment (ROI).

Types of Automation framework

Selenium, a powerful tool for browser automation, can be integrated with


various types of test automation frameworks to enhance test efficiency,

24 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

maintainability, and scalability. The main types of automation frameworks


commonly used with Selenium include:
 Linear Scripting Framework:
This is the simplest framework, where test scripts are written sequentially,
step-by-step. It's suitable for small projects or quick tests but lacks reusability
and maintainability for larger applications.
 Modular-Based Testing Framework:
This framework divides the application under test into independent modules,
and separate test scripts are created for each module. This promotes
reusability of test scripts for different modules and improves maintainability.
 Data-Driven Testing Framework:
In this framework, test data is separated from the test logic and stored in
external sources like Excel sheets, CSV files, or databases. This allows
running the same test script with multiple sets of data, reducing code
duplication and making test case management more flexible.
 Keyword-Driven Testing Framework:
This framework abstracts test actions into keywords, which are then used in
test scripts. Non-technical users can define test cases using these keywords
in a spreadsheet, making test creation more accessible and less reliant on
programming knowledge.
 Hybrid Testing Framework:
This framework combines the strengths of multiple frameworks, most
commonly data-driven and keyword-driven frameworks, and often integrates
with a Page Object Model (POM) for better organization of web elements. It
offers a robust and flexible solution for complex test automation needs.
 Behavior-Driven Development (BDD) Framework:
Frameworks like Cucumber or SpecFlow enable writing tests in a human-
readable format using Gherkin syntax (Given-When-Then). This promotes
collaboration between technical and non-technical stakeholders and ensures
tests align with business requirements.

Each framework type has its advantages and disadvantages, and the choice
depends on factors such as project size, team expertise, and specific testing
requirements. Hybrid frameworks and BDD frameworks are often preferred for
their flexibility and collaborative benefits in modern test automation practices.

25 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

UNIT- 4
Introduction to TestNG:
TestNG is an automation testing framework widely used across many
projects. NG means “Next Generation” and it is influenced by JUnit and it
follows the annotations (@).

TestNG (Test Next Generation) is a popular testing framework for Java


applications that facilitates the efficient and organized execution of test
cases. One of its key features is the ability to parameterize tests, allowing
developers to run the same test method with different sets of data.

 Powerful Testing Framework: TestNG is a popular open-source


framework that gives you a lot of control over how you write and run
your automated tests.
 Successor to JUnit: Built upon the foundation of JUnit, TestNG offers
additional features and a more user-friendly experience.
 Easy Test Control: TestNG allows you to easily define test case
dependencies. You can ensure that specific tests run before others,
mimicking real-world test workflows.
 Enhanced Functionality: Through annotations, grouping, test
sequencing, and data-driven testing, TestNG provides more powerful
and flexible ways to design your test suites.

Advantages of TestNG
 TestNG is also a Java framework that facilitates to performance of
software tests in Java.
 It is a framework that runs the tests in classes. It makes classes for
corresponding tests and then processes them.
 TestNG is an advanced framework that overcomes limitations found
in JUnit. It is also considered a flexible tool to perform tests as it
uses the same Classes to run its all tests and manages threads to
run procedures which makes the overall functioning of the checking
tests fast.

TestNG installation

TestNG can be installed as:


Using the Eclipse marketplace.
26 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

1. Go to Eclipse Marketplace
Follow the steps below to install TestNG from the Eclipse marketplace:
 Go to the Help menu in the Eclipse IDE and click on "Eclipse
Marketplace".
 Search for TestNG.

 Click on the Install button.


 Wait for some time, then a dialog box will appear.
 Click on the confirm button.

27 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Press the checkbox labelled “I accept the terms” and now click on the
Finish button.

 Installation may take a little time and you may be prompted by the
security system of Eclipse to confirm the installation.

TestNG Annotations and Listeners

Annotations were formally added to the Java language in JDK 5 and


TestNG made the choice to use annotations to annotate test classes.
Following are some of the benefits of using annotations.

TestNG identifies the methods it is interested in by looking up annotations.


Hence, method names are not restricted to any pattern or format

We can pass additional parameters to annotations. Annotations are


strongly typed, so the compiler will flag any mistakes right away.

TestNG provides both annotations and listeners as mechanisms to control


and enhance test execution. While both serve to modify or react to the
testing process, they differ in their primary function and how they are
invoked.

TestNG Annotations:

28 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Annotations in TestNG are used to define the structure and behavior of test
methods and classes. They are applied directly to methods or classes and
dictate when a particular piece of code should be executed relative to the
test lifecycle. Examples include:
 @BeforeSuite, @AfterSuite: Execute before/after all tests in a suite.
 @BeforeTest, @AfterTest: Execute before/after all tests within a <test> tag
in testng.xml.
 @BeforeClass, @AfterClass: Execute before/after all methods in a class.
 @BeforeMethod, @AfterMethod: Execute before/after each test method.
 @Test: Marks a method as a test method.
TestNG Listeners:
Listeners in TestNG are interfaces that allow you to "listen" for specific
events during test execution and perform actions in response to those
events. They provide a way to customize behavior dynamically based on
the outcome of tests or other events. Common listener interfaces include:
 ITestListener: Provides methods to react to the start/finish of tests, and the
success/failure/skip of individual test methods
(e.g., onTestStart, onTestSuccess, onTestFailure).
 IAnnotationTransformer: Allows dynamic modification of TestNG
annotations before test execution.
 IReporter: Enables custom reporting based on test results.
Key Differences:
 Invocation:
Annotations are invoked based on the defined test hierarchy (suite, test,
class, method). Listeners are invoked based on specific events triggered
during test execution (e.g., test failure, test start).
 Purpose:
Annotations primarily define the setup and teardown logic for
tests. Listeners enable reactive actions based on test outcomes or other
events, such as taking screenshots on failure or generating custom
reports.
 Implementation:

29 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Annotations are directly applied to methods or classes. Listeners are


implemented as separate classes that implement specific TestNG listener
interfaces.
In essence, annotations define what should happen and when within the
test structure, while listeners provide a mechanism to react to what
happens during the test execution.
TestNG Example

A basic TestNG example involves creating test methods in a Java class


and then defining a TestNG XML suite file to execute them.

1. Create Test Class(es):


Create Java classes containing your test methods. Mark these methods
with the @Test annotation from org.testng.annotations.Test.
// File: MyFirstTest.java
import org.testng.annotations.Test;

public class MyFirstTest {

@Test
public void testMethodOne() {
System.out.println("Executing Test Method One");
}

@Test
public void testMethodTwo() {
System.out.println("Executing Test Method Two");
}
}

2. Create testng.xml File:


Create an XML file, typically named testng.xml, to define your test
suite. This file specifies which classes and methods to include in the
execution.
Code

30 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">


<suite name="MyTestSuite">
<test name="MyApplicationTests">
<classes>
<class name="MyFirstTest"/>
</classes>
</test>
</suite>

Explanation of testng.xml:
 <suite>: The root element, representing a test suite.
 <test>: A container for one or more test classes or groups.
 <classes>: Contains a list of classes to be executed.
 <class>: Specifies a single test class by its fully qualified name

3. Execute the TestNG Suite:


You can execute the testng.xml file in various ways:
 From an IDE (e.g., IntelliJ IDEA, Eclipse): Right-click on testng.xml and
choose "Run 'MyTestSuite'".
 From the Command Line:
Code
java -cp "path/to/testng.jar;path/to/your/compiled/classes"
org.testng.TestNG testng.xml
(Replace paths with your actual locations and use : instead of ; on Unix-like
systems).

Output:
When executed, TestNG will run the specified test methods, and you will
see output similar to:
Code
Executing Test Method One
Executing Test Method Two
... (TestNG execution details and results) ..

31 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

TestNG Process Execution

TestNG process execution involves the organized and controlled running of


test cases, classes, and suites, often configured through an XML file
(testng.xml).

Key Steps in TestNG Process Execution:


 Test Case Definition:
Test methods are defined within Java classes and marked with
the @Test annotation.
 Configuration with Annotations:
TestNG annotations
like @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, @Afte
rMethod, @AfterClass, @AfterTest, and @AfterSuite are used to define
setup and teardown actions at various levels (suite, test, class,
method). These annotations dictate the execution order of these
configuration methods relative to the actual test methods.
 TestNG XML Configuration (testng.xml):
 This file is the central point for configuring test suites, tests, classes, and
methods to be executed.
 It allows for features like:
 Grouping: Organizing related tests into logical groups.
 Parameterization: Passing data to test methods.
 Parallel Execution: Running tests concurrently at the suite, test, class, or
method level to reduce execution time.
 Dependencies: Defining dependencies between test methods to ensure a
specific execution order.
 Including/Excluding: Specifying which classes, methods, or groups to
include or exclude from execution.
 Execution:
 The testng.xml file can be executed directly from an IDE (like Eclipse or
IntelliJ IDEA) or via the command line.
 TestNG reads the configuration from the testng.xml file and initiates the
execution of the specified tests.

32 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 It manages the lifecycle of the tests, including the execution


of @Before and @After annotations in their defined order.
 For parallel execution, TestNG handles the threading internally, ensuring
tests run in separate threads as configured.
 Reporting:
After execution, TestNG automatically generates detailed reports (HTML
and XML) that provide information on the test execution status, including
successes, failures, and skipped tests. These reports are typically found
in the test-output folder generated by TestNG.

TestNG provides mechanisms for controlling test execution through


batching and parallel execution, primarily configured within
the testng.xml suite file.

Batch Execution:
Batch execution in TestNG involves grouping multiple test classes or
methods to be run together in a single execution. This is achieved by listing
the desired classes or test methods within <classes> or <methods> tags
inside a <test> tag in the testng.xml file.
Code
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MySuite">
<test name="MyBatchTest">
<classes>
<class name="com.example.tests.ClassA"/>
<class name="com.example.tests.ClassB"/>
</classes>
</test>
</suite>

Parallel Execution:
Parallel execution allows TestNG to run tests concurrently, reducing overall
execution time. This is configured using the parallel attribute in
the <suite> or <test> tags in testng.xml.
 Levels of Parallelism:
 parallel="methods": Executes test methods within a class in parallel.

33 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 parallel="classes": Executes test classes in parallel.


 parallel="tests": Executes multiple <test> tags within a suite in parallel.
 parallel="instances": Executes different instances of the same test class in
parallel (relevant when using @Factory).
 Controlling Thread Count:
The thread-count attribute in the <suite> or <test> tag specifies the
maximum number of threads TestNG can use for parallel execution.
Code
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MyParallelSuite" parallel="methods" thread-count="5">
<test name="ParallelTest">
<classes>
<class name="com.example.tests.ParallelClass"/>
</classes>
</test>
</suite>

Controlled Batch Execution:


Controlled batch execution refers to the ability to define specific groupings
of tests that run together, potentially with dependencies or specific
execution orders, within a larger suite. This can be achieved by:
 Grouping Tests:
Using the groups attribute in the @Test annotation and then including or
excluding these groups in the testng.xml file.
 Dependencies:
Defining dependencies between test methods using
the dependsOnMethods or dependsOnGroups attributes in
the @Test annotation.
 Priorities:
Assigning priorities to test methods using the priority attribute in
the @Test annotation to influence their execution order within a group or
class.

34 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

UNIT-5
Advance selenium:
Advanced Selenium concepts extend beyond basic element interaction and
navigation, focusing on building robust, scalable, and maintainable
automation frameworks. Key areas include:

1. Framework Design Patterns:


 Page Object Model (POM):
A design pattern that creates an object repository for web UI elements,
improving test maintenance, reusability, and readability by separating
page interactions from test logic.
 Data-Driven Testing:
Parameterizing tests to execute them with multiple sets of test data,
enhancing test coverage and allowing for efficient testing of various
scenarios.
 Keyword-Driven Testing:
Separating test steps into keywords, making tests more readable and
allowing non-technical users to create and understand test cases.
2. Advanced Locators and Interactions:
 Advanced Locators:
Beyond basic XPath and CSS selectors, using techniques like XPath axes
for complex element identification, or leveraging relative locators
introduced in Selenium 4 for more robust element finding.
 Handling Dynamic Elements:
Strategies for interacting with elements that change their attributes or
appear/disappear dynamically.
 Synchronization Strategies:
Implementing explicit waits, fluent waits, and other synchronization
mechanisms to handle varying page load times and ensure element
availability before interaction.
3. Test Execution and Optimization:
 Cross-Browser Testing:

35 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Running tests across different browsers (Chrome, Firefox, Safari, Edge)


and versions to ensure compatibility.
 Parallel Execution:
Significantly reducing test execution time by running tests concurrently
using tools like TestNG, JUnit, or Selenium Grid.
 Selenium Grid:
A distributed testing system that allows running tests on multiple machines
and browsers simultaneously, enabling large-scale, parallel test execution.
4. Integration and Reporting:
 Integration with Testing Frameworks:
Seamlessly integrating Selenium with frameworks like TestNG or JUnit for
test organization, execution, and reporting.
 Integration with CI/CD Tools:
Integrating Selenium tests into Continuous Integration/Continuous
Delivery pipelines (e.g., Jenkins, GitHub Actions) for automated execution
and feedback.
 Advanced Reporting:
Utilizing reporting tools and frameworks to generate detailed and insightful
test reports.
5. Cloud-Based Testing:
 Leveraging cloud-based testing platforms (e.g., BrowserStack, Sauce
Labs) to perform cross-browser and cross-device testing at scale without
maintaining local infrastructure.

Selenium Grid
Selenium Grid is a smart proxy server that facilitates the parallel execution
of Selenium tests across multiple machines and browser environments. It
operates by routing WebDriver commands from a central hub to one or
more remote nodes, each configured with different browsers or operating
systems.

Key aspects of Selenium Grid:


 Parallel Execution:

36 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

It allows running multiple tests concurrently, significantly reducing the


overall test execution time.
 Cross-Browser and Cross-Platform Testing:
Enables testing on various browser versions (e.g., Chrome, Firefox,
Safari) and operating systems (e.g., Windows, macOS, Linux)
simultaneously.
 Centralized Management:
The hub acts as a central control point, managing the distribution of tests
and the availability of remote browser instances on the nodes.
 Architecture (Selenium Grid 4):
The latest version, Selenium Grid 4, features a more distributed
architecture with components like the Router, Session Map, Distributor,
Node, and Event Bus, designed for enhanced scalability and performance.
 Use Cases:
Primarily used for accelerating test cycles in web application development,
enabling efficient cross-browser compatibility testing, and supporting
large-scale test automation efforts.
Usage of Selenium Grid
Selenium Grid is a testing tool that allows you to run automated tests
across multiple machines, browsers, and operating systems in parallel. It is
primarily used to speed up test execution, improve test coverage, and
manage testing environments centrally.
Key uses of Selenium Grid

 Parallel execution: Distribute your test cases across multiple nodes to run
them concurrently. This is especially useful for large test suites that would
take a long time to run sequentially. For example, if your test suite has 100
tests, running them on 10 nodes can reduce the total execution time
significantly.

 Cross-browser and cross-platform testing: Execute tests simultaneously


across different combinations of browsers (Chrome, Firefox, Edge, Safari),
browser versions, and operating systems (Windows, macOS, Linux). This
ensures that your application provides a consistent user experience
regardless of the environment.

37 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Centralized management: A central "Hub" manages and coordinates all the


test requests and distributes them to the appropriate "Nodes" (the
machines where tests run). This simplifies test management, especially in
large teams.

 Scalability: Easily scale your testing infrastructure by adding or removing


nodes as needed. This flexibility allows you to accommodate growing test
demands and optimize resource utilization.

 Continuous integration/continuous delivery (CI/CD): Integrate Selenium


Grid with CI/CD tools like Jenkins, GitLab CI, and others. This allows you to
automatically run a suite of tests on the grid as part of your build pipeline,
providing faster feedback on code changes.

 Cloud-based testing: Use Selenium Grid with cloud-based platforms like


BrowserStack or Sauce Labs. This removes the need to maintain your own
physical or virtual infrastructure, providing instant access to a vast array of
browser and device combinations.

How Selenium Grid works

Selenium Grid operates on a hub-and-node architecture.

 Hub: The hub is the central point of the grid. It accepts test requests from
your test script (client) and routes the WebDriver commands to the correct
node for execution. There is only one hub per grid.

 Node: Nodes are the test machines (physical, virtual, or containerized) that
register with the hub. Each node is configured to run tests on a specific
browser and operating system combination.

 Process: When a test is initiated, the client sends a request to the hub with
"desired capabilities" (e.g., browser name, version, OS). The hub finds an
available node that matches these capabilities and forwards the test
commands to it. The node then executes the commands on the specified
browser.

When to use Selenium Grid

38 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

While Selenium Grid offers many benefits, it is not always necessary. Use
Selenium Grid when you:

 Have a large test suite that is slow to execute sequentially.

 Need to ensure your application works across many different browsers and
operating systems.

 Are working on a project with a fast-paced development cycle where quick


feedback on test results is crucial.

 Want to run tests on diverse environments that cannot be set up on a


single machine

Selenium Grid Architecture


Selenium Grid has a Hub and Node Architecture.

Hub

 The hub is the central point where you load your tests into.
 There should only be one hub in a grid.

39 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 The hub is launched only on a single machine, say, a computer whose OS


is Windows 7 and whose browser is IE.
 The machine containing the hub is where the tests will be run, but you will
see the browser being automated on the node.

Nodes

 Nodes are the Selenium instances that will execute the tests that you
loaded on the hub.
 There can be one or more nodes in a grid.
 Nodes can be launched on multiple machines with different platforms and
browsers.
 The machines running the nodes need not be the same platform as that of
the hub.

Selenium Grid uses a hub-node concept where you only run the test on a
single machine called a hub, but the execution will be done by different
machines called nodes.

How to setup Selenium Grid using command line

Selenium Grid is part of the Selenium suite. This tool runs test scripts in
parallel on several machines and browsers at one time. This allows for
distributed test executions over diverse environments, which further
enables a form of parallel testing. In that way, execution time is reduced.
Selenium Grid architecture relies on a central hub controlling several
nodes. Each node refers to a machine or browser instance. It is the one
performing the actual test.
This configuration will be able to test on multiple different operating
systems, versions, browsers, and devices anything that might lead to full
test coverage while still being efficient anywhere. This article covers
setting up a Selenium Grid Hub and Node for performing efficient
distributed testing.
Steps to set Selenium Grid Hub and Node
Setting up Hub and Node requires two different machines, but in this
tutorial we will use a single machine for setting up both Hub and Node,
only to make the tutorial simple and easy to understand.

40 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Step 1: Download the Selenium Server


 First of all download the latest version of "Selenium Server
(Grid)" from the Selenium
website https://www.selenium.dev/downloads/.

 The Selenium Server jar file can be placed anywhere, but it will be
convenient if we placed it in the "C: Drive" of the Hub Machine. Now
the installation of Selenium Grid is done.

Step 2: Set Up the Hub


 To launch the Hub, we need to open the Command Prompt and
change the directory to C: Drive by using "cdthe \" command,
because in this directory we will place the Selenium Server.

41 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Now type "java -jar selenium-server-4.25.0.jar hub" in the command


prompt. This command will start the Selenium Server and assign the
role of Hub to the Machine. You can replace "4.25.0" with the version
of Selenium Sever you downloaded.
 Now the hub is successfully launched and the terminal will look like
this.

 You can also verify whether the hub is successfully started or not by
simply opening your web browser and going
to "http://localhost:4444" or "http://192.168.0.103:4444/ui/". It will
look like this.

42 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 You can get the IP Address of the hub machine by using "i" command
in command prompt. Also, your hub machine IP address will
become "http://"+ "Hub Machine IP Address" + "Hub
Port" = "http://192.168.0.103:4444".

Step 3: Set Up the Node


 Now we will set up the node in the same machine. The steps will be
the same as above but the IP Address will become different or get
changed for the node machine.
 One more important thing, the Selenium Server Grid is required to be
downloaded on the Node machine as well. Although we are using
the same machine we already have the Selenium Server Grid.
 To set up the node of a different machine, log on to that machine open
the command prompt, and change the directory to C: Drive with "cd\".

43 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Now type "java -jar selenium-server-4.25.0.jar node --port 5555" in


the command prompt. This command will start the Selenium
Server and assign the role of Node to the node Machine. You can
replace "4.25.0" with the version of Selenium Sever you downloaded.
We also need to provide any free port to add the node to that port of
the Hub machine. "This command is for adding nodes in the same
machine."

 You can check if the node is added or not in the Hub machine or simply
go to "http://192.168.0.103:4444" in web browser and you will see that
the node is added successfully.

44 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

 Also you can check the command prompt of the hub machine. It will
say that the node is added successfully.

 If you want to add a node in the different machine you need to type
"java -jar selenium-server-<version>.jar node --hub http://<hub-
ip>:4444". Replace "version" with your Selenium Server version and
"hub-ip" with your hub machine IP address.
Now you have successfully set up the Hub and node machine and
successfully added the node in the hub by following these simple steps.
Key Points to Remember:
1. Always use the latest Selenium Server Grid only from the official
Selenium website https://www.selenium.dev/downloads/. In this
case, the latest version is "4.25.0"

45 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

2. Always check the compatibility of Selenium server with the Java


version. Here, we use Java 11. The minimum requirement for
Selenium Server 4 is Java 11. To download the latest Java version
visit https://www.oracle.com/java/technologies/java-se-
glance.html.
3. Follow all the steps and commands carefully, otherwise it will prompt
an error.
Conclusion
In conclusion, setting up a Selenium Grid with a Hub and Node is
essential for achieving efficient distributed testing of your web
applications. By utilizing a Hub to coordinate the execution of tests across
various Nodes, you can ensure thorough coverage across different
browsers and operating systems. This configuration not only reduces
execution time but also improves the overall quality of your testing efforts.

Designing Test Scripts That Can Run On The Grid

To design test scripts for a Grid, such as Selenium Grid, you


must write reusable, independent, and parallelizable code. The scripts use
a RemoteWebDriver to connect to a central hub, which distributes test
executions across various browsers and operating systems on its nodes.

Core scripting principles for the Grid

 Use RemoteWebDriver: Instead of instantiating a local browser driver


(e.g., ChromeDriver), connect your script to the Grid Hub using
the RemoteWebDriver class.

 Define DesiredCapabilities: Specify the browser, version, and operating


system required for your test. The Hub uses this information to match the
test with an available node.

 Parameterize tests: To maximize reuse and support cross-browser testing,


use a test runner like TestNG or JUnit to pass browser and OS details as
parameters. The test runner can then iterate through multiple environments
defined in its configuration file.

 Ensure test independence: Design each test case to be atomic, with no


dependencies on previous tests. Each test should have its own setup

46 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

(@Before) and teardown (@After) methods, which create and close a fresh
browser session. This prevents one failing test from affecting others.

 Manage test data externally: Avoid hardcoding test data. Store it in external
files (CSV, JSON), databases, or use a data provider. This prevents data
conflicts when multiple tests run simultaneously and makes it easier to
expand your test coverage.

Key design patterns

 Page Object Model (POM): This is the gold standard for creating
maintainable and scalable UI automation scripts. In POM, each web page
or major component is represented by a separate class containing its
elements (locators) and the methods that interact with them. This practice
modularizes your code and significantly simplifies maintenance when the
user interface changes.

 Data-Driven Framework: By separating test data from your test logic, you
can reuse the same test script with different data sets. This is ideal for
testing features like logins with multiple user credentials.

Example: A parallelizable login test

This example, written in Java with TestNG, demonstrates the principles of


scripting for a Grid.

1. Page Object: LoginPage.java

java
public class LoginPage {
private WebDriver driver;

public LoginPage(WebDriver driver) {


this.driver = driver;
PageFactory.initElements(driver, this);
}

@FindBy(id = "user-name")
private WebElement usernameInput;

47 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

@FindBy(id = "password")
private WebElement passwordInput;

@FindBy(id = "login-button")
private WebElement loginButton;

public void login(String username, String password) {


usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
}
}
Use code with caution.

2. Test Class: LoginTest.java

java
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.*;
import java.net.URL;

public class LoginTest {


private WebDriver driver;

@Parameters({"browser"})
@BeforeMethod
public void setup(String browser) throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName(browser);
capabilities.setPlatform(Platform.LINUX); // or WINDOWS

URL hubUrl = new URL("http://<your_hub_ip>:4444/wd/hub");


driver = new RemoteWebDriver(hubUrl, capabilities);
driver.manage().window().maximize();
}

48 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

@Test
public void testSuccessfulLogin() {
LoginPage loginPage = new LoginPage(driver);
driver.get("https://www.saucedemo.com");
loginPage.login("standard_user", "secret_sauce");
// Add assertions here
}

@AfterMethod
public void teardown() {
if (driver != null) {
driver.quit();
}
}
}
Use code with caution.

3. TestNG Configuration: testng.xml

xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Selenium Grid Suite" parallel="tests" thread-count="2">
<test name="Chrome Test">
<parameter name="browser" value="chrome"/>
<classes>
<class name="LoginTest"/>
</classes>
</test>
<test name="Firefox Test">
<parameter name="browser" value="firefox"/>
<classes>
<class name="LoginTest"/>
</classes>
</test>
</suite>
Use code with caution.

Running the tests on the Grid

49 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

1. Set up your Grid: Start the Hub and Nodes with the required browser
drivers.

2. Define a testng.xml file: In the example above, the testng.xml file


configures two parallel tests, one for Chrome and one for Firefox,
using parallel="tests".

3. Run with TestNG: Execute the suite using your build tool (Maven/Gradle) or
IDE. TestNG will run the specified tests in parallel across the Grid

Using Desiredcapabilities Object


In Selenium, a DesiredCapabilities object is a set of key-value pairs used to
specify the characteristics of the test environment. It allows you to
configure your WebDriver session for cross-browser and cross-platform
testing, such as defining the browser name, version, and operating
system.
Note: As of Selenium 4, the DesiredCapabilities class is deprecated in
favor of browser-specific Options classes, such
as ChromeOptions or FirefoxOptions. However, you can still use
capabilities with the options classes for advanced customization.

Key concepts

 Key-value pairs: Capabilities are stored as key-value pairs, typically


encoded as a JSON object, to define the testing parameters.

 Cross-browser testing: The object lets you specify the browser (e.g.,
Chrome, Firefox, Safari) and browser version for your test scripts.

 Cross-platform testing: You can define the operating system (e.g.,


Windows, macOS, Linux) on which your tests should run.

 Remote WebDriver: DesiredCapabilities are most commonly used


with RemoteWebDriver to run tests on a Selenium Grid, which distributes
tests across different machines and environments.

Example: Using DesiredCapabilities with Chrome (Selenium 3)

50 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

The following Java example demonstrates how to use


the DesiredCapabilities object to configure a ChromeDriver to accept SSL
certificates.

java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.CapabilityType;

public class SslCertificateExample {


public static void main(String[] args) {
// Create DesiredCapabilities object for the Chrome browser
DesiredCapabilities caps = DesiredCapabilities.chrome();

// Set the capability to accept all SSL certificates


caps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

// Instantiate the WebDriver with the custom capabilities


WebDriver driver = new ChromeDriver(caps);

// Your test code here


driver.get("https://self-signed-certificate.com/");

// Close the browser


driver.quit();
}
}
Use code with caution.

Example: Using browser Options (Selenium 4)

This modern approach achieves the same result as the previous example.
The ChromeOptions class, which implements the Capabilities interface, is
now the preferred method.

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

51 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

import org.openqa.selenium.chrome.ChromeOptions;

public class SslCertificateExample {


public static void main(String[] args) {
// Create ChromeOptions object
ChromeOptions options = new ChromeOptions();

// Set the option to accept insecure certificates


options.setAcceptInsecureCerts(true);

// Instantiate the WebDriver with the custom options


WebDriver driver = new ChromeDriver(options);

// Your test code here


driver.get("https://self-signed-certificate.com/");

// Close the browser


driver.quit();
}
}
Use code with caution.

Common uses of DesiredCapabilities (or Options in Selenium 4)

 Mobile testing with Appium: Define device properties, such as


the platformName, platformVersion, and deviceName, to instruct the
Appium server how to run the test.

 Running tests in headless mode: Configure the browser to run without a


visible user interface for faster test execution.

 Managing browser pop-ups: Set preferences to disable pop-up blockers or


notifications.

 Extending browser functionality: Add browser extensions for specific testing


needs.

 Configuring Selenium Grid: Specify the test environment for remote


execution on a grid of machines.

52 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Using RemoteWebDriver Object


The RemoteWebDriver object in Selenium is used for running automated
tests on a remote machine, instead of locally on the same machine where
the test script is executed. This is the core component that enables cross-
browser, cross-platform, and parallel testing using Selenium Grid or a
cloud-based service.

How RemoteWebDriver works

The architecture of RemoteWebDriver consists of a client-server model.

 Client: Your test script, using Selenium's client libraries, acts as the client. It
translates test commands into a JSON payload and sends it over the
network to the server.

 Server: The Selenium Grid acts as the server (or hub), which listens for test
requests. When it receives a request from your client script, it routes the
commands to a specific browser driver on a remote machine (or node).

 Node: This is the remote machine where the actual browser is running and
controlled by the driver. The node may have a different operating system or
browser version than the client machine.

Prerequisites for using RemoteWebDriver

To use RemoteWebDriver, you need to set up a distributed testing


environment.

1. Start a Selenium Grid hub: The hub acts as the central point for your tests.
You start it by running the Selenium standalone server JAR file with the -
role hub command.

2. Register one or more nodes: The nodes are the remote machines with
browsers and drivers installed. Each node must be registered with the hub.

3. Use a cloud-based service: Alternatively, you can use a commercial service


like BrowserStack or LambdaTest, which manages the grid infrastructure
for you.

53 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Example: How to create and use a RemoteWebDriver object

Java example

This script uses the RemoteWebDriver class to achieve the same result as
the Python example.

java
import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.By;
import java.net.MalformedURLException;

public class RemoteTest {


public static void main(String[] args) throws MalformedURLException {
// Define the URL of your Selenium Grid hub
String gridUrl = "http://localhost:4444/wd/hub";

// Define the desired browser capabilities


DesiredCapabilities caps = new DesiredCapabilities();
caps.setBrowserName("chrome");

WebDriver driver = null;


try {
// Create a RemoteWebDriver object
driver = new RemoteWebDriver(new URL(gridUrl), caps);

driver.get("http://www.google.com");
System.out.println("Page title is: " + driver.getTitle());

// Find the search box and perform a search


driver.findElement(By.name("q")).sendKeys("Selenium
RemoteWebDriver");
driver.findElement(By.name("q")).submit();

} finally {
if (driver != null) {

54 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

// Always quit the driver to close the browser and end the session
driver.quit();
}
}
}
}

Running a sample Test Case on the Grid


A test grid is an environment for executing software tests across multiple
machines, operating systems, and browsers in parallel
. This is most commonly done using Selenium Grid for automated web
application testing.

To run a sample test case on a grid, you need to set up the grid's
components, write your test script to use a RemoteWebDriver, and then
execute the test, often with a testing framework like TestNG.

Prerequisites

 Java Development Kit (JDK): Install JDK 11 or higher.

 Selenium Server JAR file: Download the latest version from the Selenium
website.

 WebDrivers: Download the appropriate browser driver (e.g., ChromeDriver,


GeckoDriver) for each browser you intend to test.

 Test Script: Create an automated test script using a framework like TestNG
or JUnit.

Step 1: Set up the grid

A Selenium Grid consists of a central Hub and one or more Nodes that run
the tests.

1. Start the Hub

1. Open a terminal or command prompt.

55 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

2. Navigate to the directory where you saved the Selenium Server JAR file.

3. Execute the following command to start the Hub.

sh

java -jar selenium-server-4.x.x.jar hub


Use code with caution.

4. Verify the Hub is running by navigating to http://localhost:4444/ in your


browser. You should see the Grid console.

2. Start the Node(s)


1. Open a new terminal or command prompt for each Node you want to run.

2. In each terminal, navigate to the directory containing the Selenium Server


JAR and the browser WebDriver.

3. Use one of these methods to start the node:

1. Autodetect drivers: The simplest method is to let the node


automatically detect the drivers in its path.

sh

java -jar selenium-server-4.x.x.jar node --detect-drivers true


Use code with caution.
2. Specify a configuration file: For more control, create a JSON
configuration file for each node.

sh

java -jar selenium-server-4.x.x.jar node --config


<path/to/your/nodeconfig.json>
Use code with caution.

4. Check the Grid console in your browser again. You should now see the
registered nodes and the browsers they support.

56 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

Step 2: Write your test case

Your test script must be configured to use a RemoteWebDriver and specify


the desired browser and platform.

Here is a sample Java test case using TestNG and a RemoteWebDriver:

java
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;

import java.net.URL;

public class SampleGridTest {

@Test
public void runChromeTestOnGrid() throws Exception {
// Define capabilities for the Chrome browser on the Windows platform
DesiredCapabilities cap = new DesiredCapabilities();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);

// Create a RemoteWebDriver instance that connects to the Hub


RemoteWebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444"), cap);

try {
driver.get("https://www.google.com");
System.out.println("Page title is: " + driver.getTitle());
} finally {
driver.quit();
}
}
}
Use code with caution.

Step 3: Run the test case

57 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur

If you are using TestNG, you can create a test suite XML file to specify
parallel execution.

Create testng.xml

Create a file named testng.xml to specify how the tests should run on the
grid.

xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Grid Parallel Test Suite" parallel="tests" thread-count="2">

<test name="Chrome Test">


<parameter name="browser" value="chrome"/>
<classes>
<class name="SampleGridTest"/>
</classes>
</test>

<test name="Firefox Test">


<parameter name="browser" value="firefox"/>
<classes>
<class name="SampleGridTest"/>
</classes>
</test>

</suite>

Execute the tests

 From your IDE: Run the testng.xml file directly from your IDE if it has
TestNG configured.

 From the command line: Navigate to your project directory and use the
TestNG command-line tool.

The grid will then assign each test to an available node that matches the
specified browser and platform, running them simultaneously.
Seenu Bommisetti

58 | P a g e

You might also like