Software Testing
Software Testing
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.
1|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
2|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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 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.
5|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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;
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("myuserna
me");
driver.quit();
}
}
7|Page
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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
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;
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
11 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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
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.");
}
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.
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
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
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.
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
20 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
21 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
UNIT-3
Test Automation Framework
22 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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).
24 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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 (@).
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
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.
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:
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
@Test
public void testMethodOne() {
System.out.println("Executing Test Method One");
}
@Test
public void testMethodTwo() {
System.out.println("Executing Test Method Two");
}
}
30 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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
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
32 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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
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:
35 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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.
36 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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.
37 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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.
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:
Need to ensure your application works across many different browsers and
operating systems.
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
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.
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
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.
41 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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".
43 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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
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.
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.
java
public class LoginPage {
private WebDriver driver;
@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;
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;
@Parameters({"browser"})
@BeforeMethod
public void setup(String browser) throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName(browser);
capabilities.setPlatform(Platform.LINUX); // or WINDOWS
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.
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.
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.
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
Key concepts
Cross-browser testing: The object lets you specify the browser (e.g.,
Chrome, Firefox, Safari) and browser version for your test scripts.
50 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.CapabilityType;
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;
52 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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.
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.
53 | P a g e
Software Testing BCA – V Sem Sri Srinivasa Degree College, Gudur
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;
driver.get("http://www.google.com");
System.out.println("Page title is: " + driver.getTitle());
} 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();
}
}
}
}
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
Selenium Server JAR file: Download the latest version from the Selenium
website.
Test Script: Create an automated test script using a framework like TestNG
or JUnit.
A Selenium Grid consists of a central Hub and one or more Nodes that run
the tests.
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.
sh
sh
sh
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
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;
@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);
try {
driver.get("https://www.google.com");
System.out.println("Page title is: " + driver.getTitle());
} finally {
driver.quit();
}
}
}
Use code with caution.
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">
</suite>
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