0% found this document useful (0 votes)
39 views30 pages

Sta - Unit - 5

Unit V discusses test automation and tools, emphasizing the importance of automated software testing in agile and DevOps environments to enhance efficiency and accuracy. It covers various types of testing, automation frameworks, and criteria for selecting automation tools, along with popular tools like Selenium and Appium. The document also outlines the advantages and disadvantages of automation testing, and highlights the benefits of automating web application testing for improved reliability and faster execution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views30 pages

Sta - Unit - 5

Unit V discusses test automation and tools, emphasizing the importance of automated software testing in agile and DevOps environments to enhance efficiency and accuracy. It covers various types of testing, automation frameworks, and criteria for selecting automation tools, along with popular tools like Selenium and Appium. The document also outlines the advantages and disadvantages of automation testing, and highlights the benefits of automating web application testing for improved reliability and faster execution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT – 5 Prepared By MAV

UNIT V
TEST AUTOMATION AND TOOLS
Automated Software Testing, Automate Testing of Web Applications, Selenium: Introducing
Web Driver and Web Elements, Locating Web Elements, Actions on Web Elements,
Different Web Drivers, Understanding Web Driver Events, Testing: Understanding
Testing.xml, Adding Classes, Packages, Methods to Test, Test Reports.

1. Automated Software Testing


Automated Testing means using special software for tasks that people
usually do when checking and testing a software product. Nowadays, many
software projects use automation testing from start to end, especially
in agile and DevOps methods. This means the engineering team runs tests
automatically with the help of software tools .
It will help to keep the testing team to make the process faster. Continuous
delivery (CD) and quickly sends the new code to users. Automated testing
is important for this because it converts the manual steps into automation.
Continuous integration (CI) checks the new code changes to prevent
issues.
CD gets after CI done everything well. Automated testing, CI & CD will
together prove that the new code is error-free and ready for deployment
quickly for the project purpose.
What is Automation Testing?
It’s a technique where the Tester writes scripts independently and uses suitable
Software or Automation Tools to test the software. It is an Automation Process of
a Manual Process. It allows for executing repetitive tasks without the
intervention of a Manual Tester.
• It is used to automate the testing tasks that are difficult to perform manually.
• Automation tests can be run at any time of the day as they use scripted
sequences to examine the software.
• Automation tests can also enter test data compare the expected result with
the actual result and generate detailed test reports.

Dept., of CSE. /III CSE/SEM-VI 1 A.V.C.C.E


UNIT – 5 Prepared By MAV
• The goal of automation tests is to reduce the number of test cases to be
executed manually but not to eliminate manual testing.
• It is possible to record the test suit and replay it when required.

Automation Testing Types


• Unit testing:
Unit testing is a phase in software testing to test the smallest piece of code
known as a unit that can be logically isolated from the code. It is carried out
during the development of the application.
• Integration testing:
Integration testing is a phase in software testing in which individual
software components are combined and tested as a group. It is carried out to
check the compatibility of the component with the specified functional
requirements.
• Smoke testing:
Smoke testing is a type of software testing that determines whether the
built software is stable or not. It is the preliminary check of the software
before its release in the market.
• Performance testing:
Performance testing is a type of software testing that is carried out to
determine how the system performs in terms of stability and responsiveness
under a particular load.
• Regression testing:
Regression testing is a type of software testing that confirms that previously
developed software still works fine after the change and that the change has not adversely
affected existing features.
• Security testing:
Security testing is a type of software testing that uncovers the risks, and
vulnerabilities in the security mechanism of the software application. It helps
an organization to identify the loopholes in the security mechanism and take
corrective measures to rectify the security gaps.
• Acceptance testing:

Dept., of CSE. /III CSE/SEM-VI 2 A.V.C.C.E


UNIT – 5 Prepared By MAV
Acceptance testing is the last phase of software testing that is performed
after the system testing. It helps to determine to what degree the application
meets end users’ approval.

• API testing:
API testing is a type of software testing that validates the Application
Programming Interface(API) and checks the functionality, security, and
reliability of the programming interface.
• UI Testing:
UI testing is a type of software testing that helps testers ensure that all the
fields, buttons, and other items on the screen function as desired.
Test Automation Frameworks
• Linear framework:
This is the most basic form of framework and is also known as the record
and playback framework. In this testers create and execute the test scripts for
each test case. It is mostly suitable for small teams that don’t have a lot of test
automation experience.
• Modular-Based Framework:
This framework organizes each test case into small individual units known
as modules each module is independent of the other, having different
scenarios but all modules are handled by a single master script. This approach
requires a lot of pre-planning and is best suited for testers who have
experience with test automation.
• Library Architecture Framework:
This framework is the expansion of a modular-based framework with few
differences. Here, the task is grouped within the test script into functions
according to a common objective.
These functions are stored in the library so that they can be accessed
quickly when needed. This framework allows for greater flexibility and
reusability but creating scripts takes a lot of time so testers with experience in
automation testing can benefit from this framework.
Dept., of CSE. /III CSE/SEM-VI 3 A.V.C.C.E
UNIT – 5 Prepared By MAV
Which Tests to Automate?
• Monotonous test:
Repeatable and monotonous tests can be automated for further use in the
future.
• A test requiring multiple data sets:
Extensive tests that require multiple data sets can be automated.

• Business critical tests:


High-risk business critical test cases can be automated and can be
scheduled to run regularly.
• Determinant test:
Determinant test cases where it is easy for the computer to decide
whether the test has failed or not can be automated.
• Tedious test:
Test cases that involve repeatedly doing the same action can be automated
so that the computer can do the repetitive task as humans are very poor at
performing the repetitive task with efficiency, which increases the chances of
error.

Automation Testing Process


1. Test Tool Selection:
There will be some criteria for the Selection of the tool. The majority of the
criteria include: Do we have skilled resources to allocate for automation tasks,
Budget constraints, and Do the tool satisfies our needs?
2. Define Scope of Automation:
This includes a few basic points such as the Framework should support
Automation Scripts, Less Maintenance must be there, High Return on
Investment, Not many complex Test Cases
3. Planning, Design, and Development:
For this, we need to Install particular frameworks or libraries, and start
designing and developing the test cases such as NUnit , JUnit , QUnit , or
required Software Automation Tools.
Dept., of CSE. /III CSE/SEM-VI 4 A.V.C.C.E
UNIT – 5 Prepared By MAV
4. Test Execution:
Final Execution of test cases will take place in this phase and it depends on
Language to Language for .NET, we’ll be using NUnit, for Java, we’ll be using
JUnit, for JavaScript, we’ll be using QUnit or Jasmine, etc.
5. Maintenance:
Creation of Reports generated after Tests and that should be documented
to refer to that in the future for the next iterations.

Criteria to Select Automation Tool


• Ease of use:
Some tools have a steep learning curve, they may require users to learn a
completely new scripting language to create test cases and some may require
users to maintain a costly and large test infrastructure to run the test cases.
• Support for multiple browsers:
Cross-browser testing is vital for acceptance testing. Users must check how
easy it is to run the tests on different browsers that the application supports.
• Flexibility:
No single tool framework can support all types of testing, so it is advisable
to carefully observe what all tool offers and then decide.
• Ease of analysis:
Not all tools provide the same sort of analysis. Some tools have a nice
dashboard feature that shows all the statistics of the test like which test failed
and which test passed. On the other hand, there can be some tools that will
first request users to generate and download the test analysis report thus, not
very user-friendly. It depends entirely on the tester, project requirement, and
budget to decide which tool to use.
• Cost of tool:
Some tools are free and some are commercial tools but many other factors
need to be considered before deciding whether to use free or paid tools. If a
tool takes a lot of time to develop test cases and it is a business-critical

Dept., of CSE. /III CSE/SEM-VI 5 A.V.C.C.E


UNIT – 5 Prepared By MAV
process that is at stake then it is better to use a paid tool that can generate
test cases easily and at a faster rate.
• Availability of support:
Free tools mostly provide community support on the other hand
commercial tools provide customer support, and training material like
tutorials, videos, etc. Thus, it is very important to keep in mind the complexity
of the tests before selecting the appropriate tool.

Popular Automation Tools


• Selenium:
Selenium is an automated testing tool that is used for Regression
testing and provides a playback and recording facility. It can be used with
frameworks like JUnit and Test-NG . It provides a single interface and lets
users write test cases in languages like Ruby, Java, Python, etc.
• QTP:
Quick Test Professional (QTP) is an automated functional testing tool to
test both web and desktop applications. It is based on the VB scripting
language and it provides functional and regression test automation for
software applications.
• Sikuli:
It is a GUI-based test automation tool that is used for interacting with
elements of web pages. It is used to search and automate graphical user
interfaces using screenshots.
• Appium:
Apium is an open-source test automation framework that allows QAs to
conduct automated app testing on different platforms like iOS, Android, and
Windows SDK.
• Jmeter:
Apache JMeter is an open-source Java application that is used to load test
the functional behavior of the application and measure the performance.

Dept., of CSE. /III CSE/SEM-VI 6 A.V.C.C.E


UNIT – 5 Prepared By MAV

Advantages of Automation Testing


• Simplifies Test Case Execution:
Automation testing can be left virtually unattended and thus it allows
monitoring of the results at the end of the process. Thus, simplifying the
overall test execution and increasing the efficiency of the application.
• Improves Reliability of Tests:
Automation testing ensures that there is equal focus on all the areas of the
testing, thus ensuring the best quality end product.

• Increases amount of test coverage:


Using automation testing, more test cases can be created and executed for
the application under test. Thus, resulting in higher test coverage and the
detection of more bugs.
This allows for the testing of more complex applications and more features can be
tested.
• Minimizing Human Interaction:
In automation testing, everything is automated from test case creation to
execution thus there are no changes for human error due to neglect. This
reduces the necessity for fixing glitches in the post-release phase.

• Saves Time and Money:


The initial investment for automation testing is on the higher side but it is
cost-efficient and time-efficient in the long run. This is due to the reduction in
the amount of time required for test case creation and execution which
contributes to the high quality of work.
• Earlier detection of defects:
Automation testing documents the defects, thus making it easier for the
development team to fix the defect and give a faster output. The earlier the
defect is identified, the more easier and cost-efficient it is to fix the defects.

Dept., of CSE. /III CSE/SEM-VI 7 A.V.C.C.E


UNIT – 5 Prepared By MAV

Disadvantages of Automation Testing


• High initial cost:
Automation testing in the initial phases requires a lot of time and money
investment. It requires a lot of effort for selecting the tool and designing
customized software.
• 100% test automation is not possible:
Generally, the effort is to automate all the test cases but in practical real
situations not all test cases can be automated some test cases require human
intervention for careful observation. There is always a human factor, i.e., it
can’t test everything like humans(design, usability, etc.).
• Not possible to automate all testing types:
It is not possible to automate tests that verify the user-friendliness of the
system. Similarly, if we talk about the graphics or sound files, even their
testing cannot be automated as automated tests typically use textual
descriptions to verify the output.
• Programming knowledge is required:
Every automation testing tool uses any one of the programming
languages to write test scripts. Thus, it is mandatory to have programming
knowledge for automation testing.
• False positives and negatives:
Automation tests may sometimes fail and reflect that there is some issue in
the system but there is no issue present and in some cases, it may generate
false negatives if tests are designed to verify that some functionality exists
and not to verify that it works as expected.
2. Automate Testing of Web Applications
Automated web application testing is a process in which testing is performed
using a set of automated testing tools. Automated testing of web applications
involves using software tools and scripts to automatically test a website's
functionality, performance, and user experience, mimicking user interactions
and verifying expected outcomes.

Dept., of CSE. /III CSE/SEM-VI 8 A.V.C.C.E


UNIT – 5 Prepared By MAV
This process reduces manual effort, increases efficiency, and improves test
accuracy, allowing for faster and more reliable testing across different
browsers, devices, and environments.

Benefits of Automated Web Application Testing:


• Time and Cost Savings:
Automation reduces the need for manual testing, saving time and resources that
can be used for other tasks.
• Improved Accuracy and Reliability:
Automated tests are repeatable and consistent, minimizing human error and
ensuring that tests are executed correctly every time.
• Faster Test Execution:
Automated tests can be run much faster than manual tests, allowing for quicker
feedback and faster development cycles.
• Increased Test Coverage:
Automation enables testers to cover a wider range of test scenarios, including
complex and repetitive tasks that might be missed during manual testing.
• Enhanced Test Maintainability:
Automated tests are easier to maintain and modify compared to manual tests,
allowing for faster adaptation to changes in the application.
• Support for Continuous Integration/Continuous Delivery (CI/CD):
Dept., of CSE. /III CSE/SEM-VI 9 A.V.C.C.E
UNIT – 5 Prepared By MAV
Automation is essential for integrating tests into CI/CD pipelines, ensuring that
tests are run automatically with every code change.
Common Tools and Techniques for Automating Web Application Testing:
• Selenium:
A widely used open-source automation framework that simulates user actions in
a web browser. Selenium WebDriver is a popular component of Selenium that
allows for writing tests in various programming languages.
• Cypress:
An end-to-end testing framework that is known for its fast execution and ease of
use. Cypress supports various testing levels, including unit, integration, and end-
to-end tests.
• Playwright:
A powerful open-source automation tool that can be used to automate browser
tasks and test web applications. Playwright supports multiple browsers,
including Chrome, Firefox, and WebKit, and offers features like parallel execution
and debugging.

• Appium:
An open-source tool for automating mobile app testing, including web
applications running within mobile browsers. Appium supports various
platforms and devices, allowing for comprehensive testing on mobile devices.
• TestComplete:
A commercial tool for automated testing of web and desktop applications,
offering a record-and-playback feature for creating tests without coding.
• Katalon Studio:
A comprehensive automation testing tool that supports various application types,
including web applications, and includes a test recorder for creating tests
without coding.
• Cucumber:
A behavior-driven development (BDD) framework that allows testers to write
tests in a clear and readable format using Gherkin syntax.
• Puppeteer:
Dept., of CSE. /III CSE/SEM-VI 10 A.V.C.C.E
UNIT – 5 Prepared By MAV
A Node.js library that provides a high-level API for controlling Chrome and
Chromium browsers. Puppeteer is often used for automating browser tasks,
including web application testing.
• BrowserStack:
A cloud-based testing platform that allows users to test web applications on a
wide range of real devices and browsers. BrowserStack offers features like
parallel testing and remote access for testing on different environments.
• LambdaTest:
Another cloud-based testing platform that supports cross-browser testing on real
browsers and devices. LambdaTest offers features like video recording and
debugging tools for analyzing test results.
3. Selenium
3.1 Introducing Web Driver and Web Elements
Introduction to selenium
What is Selenium?
Selenium is an open-source framework designed for automating web
browsers. It enables users to test website functionality across different browsers,
ensuring consistency and compatibility.

Key features of Selenium:


• Supports functional and cross-browser testing to verify seamless
performance across multiple browsers.
• Allows test script creation in various programming languages, including
Java, Python, JavaScript, Ruby, C#, and more.
• Easily integrates with testing frameworks like TestNG, JUnit, and Cucumber,
enhancing flexibility and extensibility.
Importance of Testing in Selenium
1. Language Support: Selenium allows you to create test scripts in different
languages like Ruby, Java, PHP, Perl, Python, JavaScript, and C#, among
others.

Dept., of CSE. /III CSE/SEM-VI 11 A.V.C.C.E


UNIT – 5 Prepared By MAV
2. Browser Support: Selenium enables you to test your website on different
browsers such as Google Chrome, Mozilla Firefox, Microsoft
Edge, Safari, Internet Explorer (IE), etc.
3. Scalability: Automated testing with Selenium can easily scale to cover a
wide range of test cases, scenarios, and user interactions. This scalability
ensures maximum test coverage of the application’s functionality.
4. Reusable Test Scripts: Selenium allows testers to create reusable test
scripts that can be used across different test cases and projects. This
reusability saves time and effort in test script creation and maintenance.
5. Parallel Testing: Selenium supports parallel test execution, allowing
multiple tests to run concurrently. This helps reduce the overall testing
time, making the development process more efficient.
6. Documentation and Reporting: Selenium provides detailed test execution
logs and reports, making it easier to track test results and identify areas that
require attention.
7. User Experience Testing: Selenium can simulate user interactions and
behavior, allowing testers to assess the user experience and ensure that the
application is intuitive and user-friendly.
8. Continuous Integration and Continuous Deployment (CI/CD): Selenium
can be integrated into CI/CD pipelines to automate the testing of each code
change. This integration helps identify and address issues earlier in the
development cycle, allowing for faster and more reliable releases.

Components of Selenium
Selenium Suite has 4 components namely:
1. Selenium IDE
2. Selenium RC
3. Selenium WebDriver
4. Selenium Grid

Dept., of CSE. /III CSE/SEM-VI 12 A.V.C.C.E


UNIT – 5 Prepared By MAV

Selenium WebDriver
5. Selenium WebDriver is a powerful and enhanced version of Selenium
RC which was developed to overcome the limitations of Selenium RC.
6. WebDriver communicates with browsers directly with the help of
browser-specific native methods, thereby completely eliminating the need
of Selenium RC.
7. WebDriver works closely with Selenium IDE and Selenium Grid resulting
in reliable test execution at speed and scale.

Understanding Selenium WebDriver


Selenium WebDriver is a powerful browser automation tool designed to
test web applications efficiently. Unlike Selenium RC, WebDriver directly
interacts with browser elements, making it faster and more reliable.
It supports multiple browsers, platforms, and programming languages, enabling
comprehensive testing across different environments.

When to use Selenium WebDriver


Selenium WebDriver is primarily designed to test web applications.
• Functional Testing: Test the functionality of web applications by automating
user interactions such as clicking buttons, filling out forms, navigating
pages, and verifying expected outcomes.
• Cross-Browser Testing: Test web application for consistency across different
browsers and browser versions (e.g., Chrome, Firefox, Edge, Safari)
• Cross-Platform Testing: Test the web application on different operating
systems sun as Windows, macOS, and Linux.
• Regression Testing: Test the existing functionality of the web app, whenever
a new feature is introduced.
• Data-Driven Testing: Execute the same test script with different sets of input
data to validate different scenarios.

Dept., of CSE. /III CSE/SEM-VI 13 A.V.C.C.E


UNIT – 5 Prepared By MAV
• Parallel Testing: Selenium WebDriver can be integrated with tools like
Selenium Grid to execute tests in parallel across multiple browsers and
platforms, reducing testing time.
• Complex User Flows: Simulate complex user workflows or interactions
that need to be tested repeatedly.
• Integration with Continuous Integration (CI) Pipelines: Selenium
WebDriver can be seamlessly integrated into your CI/CD pipeline, enabling
automated testing with every code change and ensuring code quality.
• UI/UX Testing: Automate user interface (UI) testing, ensuring that the
visual elements and layout of your application are consistent.

Architecture of Selenium WebDriver (Selenium 3)


WebDriver Architecture is made up of four major components:

• Selenium Client library: Selenium provides support to multiple libraries


such as Ruby, Python, Java, etc as language bindings
• JSON wire protocol over HTTP: JSON is an acronym for JavaScript Object
Notation. It is an open standard that provides a transport mechanism for
transferring data between client and server on the web.
• Browser Drivers: Selenium browser drivers are native to each browser,
interacting with the browser by establishing a secure connection. Selenium
supports different browser drivers such as ChromeDriver, GeckoDriver,
Microsoft Edge WebDriver, SafariDriver, and InternetExplorerDriver.
Dept., of CSE. /III CSE/SEM-VI 14 A.V.C.C.E
UNIT – 5 Prepared By MAV
• Browsers: Selenium provides support for multiple browsers like Chrome,
Firefox, Safari, Internet Explorer etc.

JSON wire protocol helps Selenium Language Bindings communicate with the
Browser Drivers and thus automate interactions on real browsers.

Browsers Supported in Selenium WebDriver


Selenium supports these Browsers:
• Google Chrome
• Mozilla Firefox
• Safari
• Internet Explorer
• Microsoft Edge
3.2 Locating Web Elements
Locating the target web element is a crucial step in automating user
interactions on a web page. Selenium offers 7 locating strategies that we can use
to locate the target web element precisely on a web page.
Here are the 7 locating strategies:
1. Locating By ID.
2. Locating By Class Name.
3. Locating By Name.
4. Locating By Tag Name
5. Locating By CSS Selector.
6. Locating By XPath.
7. Locating By Link Text And Partial Link Text.

1. Locating By ID
The ID attribute of an HTML element is a unique identifies, the id attribute is
assigned to a specific element and should be unique on a web page and this
makes it an ideal choice for locating an element because it guarantees that you're
targeting the exact element you intend to interact with.

Dept., of CSE. /III CSE/SEM-VI 15 A.V.C.C.E


UNIT – 5 Prepared By MAV
• Searching for an element using its ID is generally faster than other methods
such as XPATH or CSS Selector because it leverages native browser functions
optimized for this purpose.
• To locate an element by ID we use By.ID locator provided by the By class.
• By is a class that provides a set of locating strategies to locate web elements
on a web page.
Syntax:
element=driver.find_element(By.ID, "element_id")

2. Locating By Class Name


The class attribute is one of the most commonly used in attribute in HTML
.The class attribute allows multiple elements on a webpage to share a common
styling. While classes can be shares with other elements, each element class value
should be unique within its scope. This uniqueness makes it a right choice for
locating elements on a web page.
• To locate an element by CLASS we use By.CLASS_NAME locator provided by
the By class.
• By is a class that provides a set of locating strategies to locate web elements
on a web page.
Syntax:
element=driver.find_element(By.CLASS_NAME, "element_class_name")

3. Locating By Name
The name attribute of an HTML element is an identifier like a label . Unlike id
,class the name attribute doesn't necessarily unique within a web page. They are
often used for naming form elements and is used in HTML forms to handle form
controls such as input fields , radio button etc. The name attribute is essential for
from submission and used to associate input data to specific name. This makes
name a useful locator strategy especially when dealing with form submissions.
• To locate an element by Name we use By.NAME locator provided by the By
class.

Dept., of CSE. /III CSE/SEM-VI 16 A.V.C.C.E


UNIT – 5 Prepared By MAV
• By is a class that provides a set of locating strategies to locate web elements
on a web page.

Syntax:
element=driver.find_element(By.NAME, "element_name")

4. Locating By Tag Name


Every element in HTML document is identified by a TAG NAME. Tag Name are
used to define the purpose and type of an element in a webpage. Tag Name lets
us locate an element on a web page using the Tag Name like button , useful when
we are looking for a specific element in our web page. Common HTML tag names
are "div", "p", "input", "button" and many more.
• Locating an element with tag name is useful specially when you want to
interact with a group of elements that share a common tag name.
• For example if we are testing a web application with multiple input fields , we
can locate all the input fields by their "input" tag name ,this makes it easier to
perform actions like filling out forms or validating inputs.
• To locate an element by TAG NAME we use By.TAG_NAME locator provided by
the By class.
• By is a class that provides a set of locating strategies to locate web elements
on a web page.
Syntax:
element=driver.find_element(By.TAG_NAME, "element_tag_name")

5. Locating By CSS Selectors


CSS Selectors are the patterns that used to select and style HTML elements in
web development. CSS selectors allows us to target elements in a web page by
their attributes ,position and hierarchy on a web page.
Some common CSS selectors are:
• Element Selectors: Selects an element based on their HTML tag name. For
example 'p' selects all <p> elements.

Dept., of CSE. /III CSE/SEM-VI 17 A.V.C.C.E


UNIT – 5 Prepared By MAV
• Class Selectors: Selects an element with a specific class attribute. For
example '.btn' selects all elemets with 'class="btn"'.
• ID Selector: Selects an element with specific id attribute . For example
"#header" will select all the element with 'id="header"'.
• Descendent Selector: Selects an element that is a descendant of another
element. For example, 'ul li' selects all '<li>' element within a '<ul>' element
To locate an element by CSS Selector we use By.CSS_SELECTOR locator provided
by the By class. By is a class that provides a set of locating strategies to locate
web elements on a web page.
Syntax:
driver.find_element(By.CSS_SELECTOR, "element_css_selector")

6. Locating By XPath
XPath (XML Path Language) is a powerful and one of the best locating strategy in
Selenium for identifying elements on a web page. XPath is a language used for
navigating and querying XML documents but its widely used in web scrapping
and automation.
• In selenium XPath is a valuable tool for selecting elements based on their
attributes , position and relationship within the HTML structure of a web
page.
• XPath is a powerful strategy but its slower than other locators. However its a
good choice when other locating strategy don't work or specially when the
elements don't have reliable ID's, classes, or names.
• While using XPath in Selenium we'll often inspect the webpage's HTML source
code to identify the attributes that uniquely identify the element we want to
interact.
• These attributes can be id, class, or name.
• XPath provides a powerful way to combine these attributes to pinpoint
elements accurately.
Syntax-
element=driver.find_element(By.XPATH, "element_xpath")

Dept., of CSE. /III CSE/SEM-VI 18 A.V.C.C.E


UNIT – 5 Prepared By MAV
7. Locating using Link Texts and Partial Link Texts
Link Texts as the name suggests are primarily used to locate anchor tags '<a>'
elements on a webpage. Anchor tags are primarily used for hyperlinks (those
which navigate us to different page or resource on a website).
• To locate an element by its link text we provide the exact text that contained
within the anchor elements. Selenium then searches the web page for an
anchor element that matches with the text you provided.
• Partial link texts are similar to link texts but it allows us to search for
elements by providing only a part of the link text instead of the full text.
• This can be particularly used when we want to locate element with dynamic
or changing texts.
• By using By.LINK_TEXT we can find the elements with exact link text, while
By.PARTIAL_LINK_TEXT we can find elements with partial match of link texts.
Syntax:
element = driver.find_element(By.LINK_TEXT, "element_link_text")

3.3 Actions on Web Elements


The Action class handles advanced user interactions in Selenium, like
mouse movements, keyboard inputs, and context-click (right-click) actions. More
control and flexibility in automated testing scenarios are possible since it makes
it possible to simulate intricate user interactions that are impossible to
accomplish with simple WebDriver instructions.

Methods of Action Class


The Action class has many methods for different actions:
• click(WebElement element): The click() function is for clicking on a web
element. The purpose of this technique is to mimic a left click on a designated
web element. It is frequently used to interact with clickable items like
checkboxes, buttons, and links.
• doubleClick(WebElement element): doubleClick() helps do a double click
on a web element. A specific web element can be double-clicked using the

Dept., of CSE. /III CSE/SEM-VI 19 A.V.C.C.E


UNIT – 5 Prepared By MAV
DoubleClick technique. It is frequently employed in situations when a double
click is necessary to start a process or event.
• contextClick(WebElement element): contextClick() lets you right-click on a
web element. This technique mimics a context-click, or right-click, on a
designated web element. It comes in useful when engaging with context
menus and initiating right-click operations.
• moveToElement(WebElement element): moveToElement() moves the
mouse pointer to the middle of a web element. The mouse pointer is moved to
the center of the designated web element using the moveToElement function.
Hovering over components that display hidden options or activate dropdown
menus is typical usage for it.
• dragAndDrop(WebElement source, WebElement target): dragAndDrop()
allows dragging one element and dropping it onto another. By dragging an
element from its present place and dropping it onto another element, you can
execute a drag-and-drop operation using this approach. It can be used to
simulate user operations like rearranging objects or transferring components
between containers.
3.4 Different Web Drivers
Here are the different types of drivers of Selenium WebDriver:
ChromeDriver:
The ChromeDriver is built for the Chrome web browser and is supported by
the Chromium project.
ChromiumDriver
The ChromiumDriver is a WebDriver implementation used to control the
Chromium browser running on a local machine. Chromium is separate from
Chrome and is an open-source project that forms the basis of the Chrome web
browser.
EdgeDriver:
EdgeDriver is a WebDriver implementation for the Microsoft Edge browser,
making it possible to automate the Edge browser on Windows. This makes
EdgeDriver more reliable and stable for web automation than most other solutions
based on the Chromium engine.
Dept., of CSE. /III CSE/SEM-VI 20 A.V.C.C.E
UNIT – 5 Prepared By MAV
EventFiringWebDriver:
EventFiringWebDriver is a subclass of WebDriver in the Selenium library. It
is used to register event listeners for WebDriver actions, such as clicks, navigation,
and element interactions.
FirefoxDriver:
FirefoxDriver is the WebDriver implementation for the Mozilla Firefox
browser. FirefoxDriver uses the GeckoDriver executable to interact with the
Firefox browser. It allows for the automation of Firefox on various platforms, such
as Windows, macOS, and Linux.

InternetExplorerDriver:
InternetExplorerDriver is the WebDriver implementation for the Microsoft
Internet Explorer browser. It enables automation of the Internet Explorer browser
on the Windows operating system. InternetExplorerDriver uses the IE driver
server executable to interact with the Internet Explorer browser.
OperaDriver:
OperaDriver is the WebDriver implementation for Opera, making it possible
to automate Opera on various platforms such as Windows, macOS, and Linux. It
uses the OperaChromiumDriver executable to interact with the Opera browser.

RemoteWebDriver:
RemoteWebDriver is a class in the Selenium WebDriver library that allows
you to run WebDriver scripts on a remote machine. It enables you to execute your
Selenium scripts on separate devices or in a cloud environment, and you can use it to distribute
your tests across multiple devices for faster execution.

SafariDriver:
SafariDriver is an implementation of the WebDriver protocol for Apple
Safari. This means you can use it for automation testing of your website on macOS.
You do not need to install any additional software; SafariDriver is built into Safari
on macOS and enabled by default.

Dept., of CSE. /III CSE/SEM-VI 21 A.V.C.C.E


UNIT – 5 Prepared By MAV
3.5 Understanding Web Driver Events
Selenium WebDriver events provide a mechanism to track and react to
various actions and occurrences during test script execution.
To do this, Selenium
provides EventFiringWebDriver and WebDriverEventListener. EventFiringWebDri
ver is a wrapper around WebDriver that allows the firing of events.

WebDriverEventListener is an interface that test developers can implement to


listen for and handle these events.

1. EventFiringWebDriver:
• Purpose:
This class acts as a wrapper around the standard WebDriver object. It allows for
the creation of events that are triggered during certain WebDriver actions (like
navigating to a URL, clicking an element, etc.).
• How it works:
When an event-firing WebDriver action is performed, EventFiringWebDriver fires
an event. These events can be tracked and handled by any registered listeners.
2. WebDriverEventListener:
• Purpose:
This interface defines methods that implementers can override to receive
notifications about events fired by EventFiringWebDriver.
• How it works:
To listen for WebDriver events, you need to create a class that implements
the WebDriverEventListener interface. Then, you need to register an instance of
this class with the EventFiringWebDriver object.
• Methods:
The WebDriverEventListener interface includes methods
like beforeNavigateTo(String url, WebDriver driver), afterNavigateTo(String url,
WebDriver driver), beforeClick(WebElement element, WebDriver driver),
Dept., of CSE. /III CSE/SEM-VI 22 A.V.C.C.E
UNIT – 5 Prepared By MAV
and afterClick(WebElement element, WebDriver driver), which can be
implemented to handle specific events.
How to use WebDriver events:
1. Create an EventFiringWebDriver instance:
Wrap your regular WebDriver instance with an EventFiringWebDriver instance.
2. Create a WebDriverEventListener implementation:
Implement the WebDriverEventListener interface and provide the logic for
handling the events.
3. Register the listener:
Register your WebDriverEventListener implementation with
the EventFiringWebDriver object.
4. Perform actions:
Use the EventFiringWebDriver to perform actions on the browser. The registered
listeners will be notified when events are fired.

4.Testing: UnderstandingTesting.xml
TestNG is a popular testing framework in Java that provides several features for
writing test cases. One of the key components of TestNG is the `testng.xml` file,
which allows for easy configuration and control over test execution.
What is testng.xml file?
The `testng.xml` file is a configuration file used by the TestNG testing framework in
Java. It allows you to define and organize your test suite, specify which test classes
to run, and configure various aspects of your test execution. This XML file provides
a way to manage complex test scenarios and control the test execution in a more
structured way.
It allows for:
• Grouping test cases into test suites and test groups.
• Specifying the order of execution.
• Controlling parallel execution and setting thread count.
• Filtering which test methods to run.
Basic Structure of testng.xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">

Dept., of CSE. /III CSE/SEM-VI 23 A.V.C.C.E


UNIT – 5 Prepared By MAV
<suitename="MyTestSuite"parallel="methods"thread-count="2">
<testname="Test1">
<classes>
<classname="com.example.tests.TestClass1"/>
<classname="com.example.tests.TestClass2"/>
</classes>
</test>
</suite>
What is the Purpose of the testng.xml File?
Following are the main purpose of the testng.xml file.
1. Centralized Configuration: Instead of hardcoding configurations into
individual test classes, the testng.xml file allows you to configure your entire
test suite in a single place. This makes it easier to adjust test settings, change
the execution order, or add/remove tests without modifying the test code itself.
2. Modularity: The file lets you create multiple test groups, suites, and sub-suites,
which enables modular testing. This is useful for organizing tests based on
functionality, teams, or release cycles.
3. Control Over Execution: You can use the testng.xml to set the execution
order of test cases, manage parallel execution, and even specify conditions
under which certain tests should or shouldn't run (e.g., based on environment,
priority, or dependency).
4. Filter and Fine-tune Tests: By specifying only certain methods or classes to
run, you can selectively execute parts of your test suite. This is beneficial
when you’re testing specific features or modules.
5. Ease of Maintenance: The file promotes better maintenance of your test
suite, as you can modify test configurations without altering the test scripts.
This separation of concerns makes scaling and updating test suites more
manageable.

5.4.2 Adding Classes


To add test classes to a testng.xml file, you'll use the <class> or <classes> tags within
the <test> tag. The <test> tag defines a test suite, and within that, you can specify classes or
groups of classes to run.
Dept., of CSE. /III CSE/SEM-VI 24 A.V.C.C.E
UNIT – 5 Prepared By MAV
Steps
1. Open your testng.xml file: Locate the XML file where you want to add the test classes.
2. Navigate to the <test> tag: Find the <test> tag within the testng.xml file. This tag defines a test
suite and will contain the configuration for running tests.
3. Add <class> or <classes>:
o <class> (for single classes): If you want to run a single test class, you can add a <class> tag
inside the <test> tag. The name attribute of the <class> tag should be the fully qualified name
of your class (e.g., com.example.MyTestClass).
o <classes> (for multiple classes): If you want to run multiple test classes, you can use
the <classes> tag. Inside the <classes> tag, you can add one or more <class> tags to specify the
classes you want to include.
4. Specify class name(s): Use the name attribute within the <class> tags to specify the fully
qualified name of your test classes.
5. Save the testng.xml file: Save the changes to the file.
Example:
Code
<suitename="MyTestSuite">
<testname="MyTest">
<classes>
<classname="com.example.MyFirstTest"/>
<classname="com.example.MySecondTest"/>
</classes>
</test>
</suite>
In this example, the MyTest test suite will run the MyFirstTest and MySecondTest classes.

5.4.3 Packages
Adding Packages to testng.xml file, will explain you about creating and
configuring TestNG test suite with packages which are developed/created in the
java project.
A Package may contain one or more classes in it. With this testng.xml
configuration file we can include all the classes belongs to a particular package
or its sub packages to the test suite.
1.Create a java project with multiple packages and multiple classes in each
package.
Dept., of CSE. /III CSE/SEM-VI 25 A.V.C.C.E
UNIT – 5 Prepared By MAV

2.In the above project; created 3 packages called (com.test.firstpackage,


com.test.secondpackage and com.test.thirdpackage) and each package had 2
classes.

3.Now create a testng.xml file (here the xml file name is “testng-packages.xml”)
with below code/configuration content.

1
<?xml version="1.0" encoding="UTF-8"?>
2
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
3
<suite name="Suite">
4 <test name="PackageTest">
5 <packages>

6 <package name="com.test.firstpackage"/>

7 <package name="com.test.secondpackage"/>

<package name="com.test.thirdpackage"/>
8
</packages>
9
</test> <!-- Test -->
10
</suite> <!-- Suite -- >
11
In the above code, packages will be reside in the “packages” tag and the each individual
package will be in the “package” tag with “name” attribute.

4. Now execute the “testng-packages.xml” file from eclipse as TestNG suite.


Then you can see the following output.

Dept., of CSE. /III CSE/SEM-VI 26 A.V.C.C.E


UNIT – 5 Prepared By MAV

This way we can configure the packages in the testng xml configuration file to execute the
scripts as packages and can analyse the test results.

5.4.4 Methods to Test


TestNG is a popular Java testing framework that stands for Test-Next
Generation. It is an advanced form of JUnit, and offers comprehensive features,
especially when it comes to integration tests.

Include Test Methods


@Test annotation
The @Test annotation marks a method as a unit test in TestNG. It tells the TestNG execution
environment to include the following method in the test execution as a unit test.
@Testpublic void LoginTest() { //test body here}
The @Test annotation has several properties that can be used to execute it as we want. The
three most important properties of @Test annotation are:
1. enabled: This property is like a switch. It turns the method on or off. If you set
enabled=false, the test method will be stopped from execution and act like it does not
exist.
2. dependsOnMethods: This property allows you to specify test dependency and control the
order of Tests. It takes an array of Strings as arguments. The strings are the names of the
methods the following method depends on. The execution of these must be complete
before we try to run the succeeding method.
3. groups: This property is a string array that contains the names of the groups the particular
method belongs to. Groups are specified as follows:
@Test(groups={"A","B"},
Dept., of CSE. /III CSE/SEM-VI 27 A.V.C.C.E
UNIT – 5 Prepared By MAV
enabled=true)public void LoginTest() {
//test body here}
The above example portrays that the method LoginTest belongs to the groups 'A' and 'B'.

Exclude Test Methods


Introduction to excluding test methods
Excluding test methods prevents them from running during test execution. We have
already seen how we can prevent groups of tests from running in the previous section. In this
section we will look at how we can exclude one test at a time.
Explanation of @Test(enabled = false) annotation
Example:
@Test(enabled=true/false) public void LoginTest() {
//body of the test-method }

5.4.5 Test Reports.


TestNG Reports are auto-generated HTML reports that provide a detailed
summary of test case execution when using TestNG with Selenium.
These reports help assess the performance and reliability of a project by
presenting the status of individual test cases—whether they passed, failed, or were
skipped.
TestNG offers various ways to generate reports, including its built-in HTML
reports, console output, and the ability to integrate with third-party reporting
tools like Extent Reports and Allure.
These reports provide insights into test execution, including the number of passed,
failed, and skipped tests, as well as details about each test case.

TestNG Reporting Options:


• Built-in HTML Reports:
TestNG generates HTML reports by default after test execution, providing a summary of the
test suite's results.
• Console Output:
The console displays a concise summary of the test execution, including the number of tests
passed, failed, and skipped, along with any error messages.
• Third-Party Reporting Tools:
Dept., of CSE. /III CSE/SEM-VI 28 A.V.C.C.E
UNIT – 5 Prepared By MAV
• Extent Reports: A popular open-source library for generating detailed and visually appealing
HTML reports, which can be easily integrated with TestNG.
• Allure: Another open-source framework for generating rich HTML reports that provide both
high-level and detailed views of test results.
ReportNG:
A plugin for TestNG that provides a simple, color-coded HTML report as an alternative to the
default TestNG HTML report.
JUnit XML Reports:
TestNG can also generate JUnit XML reports, which are compatible with CI/CD tools like
Jenkins.
Custom Reporters:
TestNG allows developers to create custom reporters by implementing
the IReporter interface.
Key Features of TestNG Reports:
• Detailed Summary:
Provide a summary of the test execution, including the number of passed, failed, and skipped
tests.
• Test Case Details:
Offer information about individual test cases, including their status, execution time, and any
error messages.
• Visualizations:
Some reports, like those generated by Extent Reports and Allure, offer visual representations
of test results, such as pie charts and trend graphs.
• Customization:
TestNG allows for customization of report content and appearance, including the ability to
add custom fields and logos.

Example: Using the Reporter class:


The Reporter class in TestNG can be used to log messages to the test execution
reports. These messages can be used to provide additional information about the test execution,
such as the version of a driver used or input parameters passed to a function.
import org.testng.Reporter;

public class MyTest {

Dept., of CSE. /III CSE/SEM-VI 29 A.V.C.C.E


UNIT – 5 Prepared By MAV
@Test
public void testMethod() {
Reporter.log("This is a test log message.");
}
}

Dept., of CSE. /III CSE/SEM-VI 30 A.V.C.C.E

You might also like