UNIT-V - Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION

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, TestNG: Understanding TestNG.xml, Adding
Classes, Packages, Methods to Test, Test Reports.

5.1 AUTOMATED SOFTWARE TESTING


Automated software testing is the method of automatically reviewing
and validating software products, such as web and mobile applications.
This process ensures that they meet all predefined quality standards for
code style, functionality, and user experience. Test automation replaces
manual human activity with systems. Even though tests, like regression or
functional testing, can be done manually, automating the process will
reduce the time taken to perform the tests. Moreover, it takes less time to
perform exploratory tests and more time to maintain test scripts, thus,
increasing the overall test coverage.

Difference Between Manual Testing vs Automated Testing


Below are some of the differences between manual testing and automated
testing:

Parameters Manual Testing Automated Testing


Reliability Manual testing is not accurate Since it is performed by
at all times due to human third-party tools and/or
error, thus it is less reliable. scripts, therefore it is more
reliable.
Investmen Heavy investment in human Investment in tools rather
t resources. than human resources.
Time Manual testing is time- Automation testing is time-
efficien consuming due to human saving as due to the use of
cy intervention where test cases the tools the execution is
are generated manually. faster in comparison to
manual testing.
Programmin There is no need to have It is important to have
g programming knowledge to programming knowledge to
knowledge write the test cases. write test cases.
Regression There is a possibility that the When there are changes in
testing test cases executed the first the code, regression testing
time will not be able is done to
to catch the regression bugs catch the bugs due to
due to the frequently changing changes in the code.
requirements.

Purpose of Automation Testing:


Automation testing serves several important purposes in the software
development lifecycle. Let's explore some key reasons why organizations
embrace automation testing:
Panimalar Engineering College 1
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
1. Increased Test Coverage: Automation testing enables a broader scope of
test coverage. Organizations can leverage a test automation platform and
use it to design test scripts to cover various scenarios and test cases,
ensuring thorough validation of software functionality. With automated
tests, organizations can achieve higher levels of test coverage, resulting in
improved software reliability.
2. Consistency and Reusability: Automation testing ensures consistent
test execution by removing the element of human error. Using test
automation platform to automate testing, you can reuse test scripts across
multiple test cycles and different software versions. This reusability not only
saves time but also promotes consistency in testing, enabling accurate
comparison of results over time.
3. Early Detection of Defects: Automation testing enables early detection
issues. By running automated tests at different stages, such as during
integration or regression testing, potential
bugs can be identified and addressed promptly. Early defect detection helps
in reducing the costs.

Kinds of Tests should be Automated:


While testing an application/software, testers cannot automate all
processes involved in the testing cycle. Some tests need human supervision
and involvement to get better results. Using test automation platforms to
automate testing is not an alternative to manual testing but helps and
supports the entire testing team by reducing the workload.

In order to determine whether a test is suitable for automation, testers can


check if it fits the following criteria:
• The tests should be highly repetitive and take a long period of time to
perform if it is done manually
• The testing path must be predictable, as it has been verified earlier through
manual testing
• The tests that involve the testing of frequently used features that
introduce high-risk conditions
• The tests that require multiple datasets and run on several different
hardware or software platforms and configurations
• Tests that are not possible for human manual testing, e.g., thousands of
concurrent users trying to log in at the same time
If a test meets all these criteria mentioned above, you can consider leveraging
test automation platforms for automation.

Various Types of Automated Software Testing:


1. Unit Testing:
The testing of each unit of the software application is known as unit testing.
As it is the first level of testing, you can use test automation platforms to
automate it. This type of testing is used to validate unit components with
their performance. Primarily, unit testing is performed during the
development phase.
2. Smoke Testing:
Smoke testing is usually done on a build software received from the
development team. The focus of the smoke tests is to check whether the
build software is stable or not. If the software passes this test, then testers
can proceed with further testing.
3. Integration Testing:
Panimalar Engineering College 2
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
Integration testing is the testing process that is performed after unit testing.
This test ensures that units or individual components of the software are
tested in a group and work well as a whole. This test is used to detect
defects at the time of interaction between integrated components or units.
4. Regression Testing
Regression testing is both functional and non-functional type of testing. It
verifies the code changes that do not impact the software's existing
functionality. This testing ensures that the software works fine with new
functionality, bug fixes, or code changes in the existing feature. With
HeadSpin’s test automation platform, testing teams can perform regression
automation testing for their apps/websites. HeadSpin's Regression
Intelligence is a powerful comparison tool for analyzing degradation across
new app builds, OS releases, feature additions, locations, and more. Using
the test automation platform, testers can also compare build over build,
location over location, network over network, and device over device
performance of their apps/websites.
5. API Testing
The application programming interface (API) is the connection between all
the other systems that software needs to function. This testing verifies all
APIs. API testing is mainly used to test the programming interfaces'
functionality, reliability, performance, and security.
While executing API testing with the HeadSpin Platform, the API usage
monitoring feature
will help testers keep track of how their APIs are being used by applications
or track the impact of 3rd party APIs on application performance.
6. Security Testing
Security testing is also functional and non-functional in nature. It detects
the weaknesses and threats in the software. This testing can block the
attacks from hackers and ensure the security of the software.
7. Performance Testing
Performance testing records the system performance of the software in terms
of responsiveness and stability under a specific workload. The main
parameters checked under this testing include the software's speed,
robustness, and reliability.
8. Acceptance Testing
Acceptance testing is used to check how end users will respond to the final
software product. Usually, this is the last type of testing used before a
software/application is released.
9. UI Testing
UI testing checks and verifies visual elements of apps/web pages to validate
proper functionality and expected performance. This testing is done after
the complete development of the application/software.
With global device infrastructure and quality of experience (QoE) insights,
HeadSpin enables organizations to deliver flawless UI experiences.
Organizations can use the HeadSpin Platform to perform UI testing on real
devices and record test sessions. This feature will give them real- time
insights into the performance of their applications.

Automated Software Testing Tools


In software development, ensuring the quality and reliability of software
through testing is a crucial step. Automated testing tools have become
indispensable in achieving this goal efficiently. These tools speed up the
testing process and enhance its accuracy. Below, we introduce a selection of
Panimalar Engineering College 3
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
prominent automated software testing tools, each with its unique features
and capabilities:
Selenium - A staple in the automated testing tool arsenal, Selenium
supports multiple languages and browsers, focusing on web application
testing. It allows for creating complex test scripts that can mimic a wide
range of user actions.
TestComplete - Offering a comprehensive testing solution, TestComplete
supports desktop, mobile, and web applications. It's known for its robust
record and playback feature, making it accessible to testers without
extensive scripting knowledge.
JUnit - A fixture in the Java ecosystem, JUnit facilitates unit testing with
simplicity and ease of use. Its annotations and assertions make it a go-to for
developers looking to implement test- driven development (TDD).
Cypress - A modern web testing tool designed to work exclusively with web
applications. Cypress offers a unique testing experience by running tests in
the same run-loop as the application, leading to faster and more reliable
tests.
Appium - Focused on mobile application testing, Appium supports
automation on iOS and Android platforms. It works well for applications
written in any framework, making it a versatile choice for mobile testing.
Robot Framework - An open-source, keyword-driven test automation
framework, Robot Framework is designed for acceptance testing and
acceptance test-driven development (ATDD). It's easy to use for those new to
automated testing while still powerful enough for complex test scenarios.
Postman - While primarily known as an API development tool, Postman also
offers automated testing capabilities for RESTful APIs. Its user-friendly
interface allows for easy creation, management, and execution of API tests.
WebDriverIO - A JavaScript-based testing utility, WebDriverIO is designed
for front-end testing, making it an excellent choice for testing web
applications. It integrates seamlessly with modern web development tools
and supports BDD/TDD.
QTP/UFT (Unified Functional Testing) - Developed by Micro Focus, UFT is
a widely used tool for functional and regression testing, offering a rich set of
features for GUI testing. It supports a wide range of applications, making it
ideal for enterprises.
Cucumber - Emphasizing behavior-driven development (BDD), Cucumber
allows for the specification of application behavior in plain language. This
makes tests easy to read and understand, bridging the gap between
business stakeholders and the technical team.

Different Types of Test Automation Frameworks:


In the test automation process, testing frameworks play a crucial role.
These frameworks include guidelines for testers/developers in coding
standards, repository management, and handling of test data. The main
focus of these frameworks is to reduce maintenance costs and testing efforts
and achieve a high return on investment for the testing teams.
Let's look at the different types of automated software testing frameworks
that many organizations use to achieve a good testing environment.
1. Linear Automation Framework
The linear test automation framework guides testers to create functions
without writing codes, and the steps in this framework are given in
sequential order. While testing with this framework, testers record every step
and play the script back automatically to repeat the test.
Panimalar Engineering College 4
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
2. Modular-based Testing Framework
In the modular-based testing framework, testers need to divide the
application/software under test into separate units or sections. These
separate units or sections are tested in isolation. Individual test scripts are
created for each part, and after testing, all parts are combined to build larger
tests that represent various test cases. The most important step in this
framework is creating an abstraction layer, which avoids changes in
individual sections affecting the overarching module.
3. Data-driven Framework
In the data-driven framework, the test data are separated from script logic,
and testers can store all the data externally. With this framework, whenever
testers need to test application/software multiple times with different data
sets, they can use the data stored in external data sources. The main
external data sources used in this framework are Excel Spreadsheets, Text
Files, CSV files, SQL Tables, or ODBC repositories.
4. Keyword-driven Framework
While using the keyword-driven framework for automated testing, all
functions of the application/software undergoing the test are written out in
the table with specific instructions in the order of the test that needs to be
performed. In this framework also, test data are separated from script logic.
Keywords are also stored in the external data table. These keywords
represent the various actions that are being performed to test the GUI of an
application. This framework requires a shared object repository to navigate
the objects to their associated actions.
5. Hybrid Testing Framework
The hybrid framework is a combination of the already mentioned
frameworks. This type of framework is used to leverage some frameworks'
advantages and mitigate others' weaknesses.

Automation Testing Process


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?
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
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
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.
Maintenance: Creation of Reports generated after Tests and that should be
documented to refer to that in the future for the next iterations.

5.2 AUTOMATE TESTING OF WEB APPLICATIONS


Testing a web application is a highly crucial and essential part of software
development. It is a software practice that can be automated with the
combination of different tools related to it. It eventually reduces the need for
human intervention and leads to incredible speed, reliability, and efficiency
in it. It can be implemented and accomplished using various types of
Panimalar Engineering College 5
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
software automation testing tools and types of it for that particular purpose
and eventually increase the performance and enhance the user interface of
it.

Types of Web App Testing that can be automated:


Given the complexity and variety of modern web applications, a multifaceted
testing approach is essential. This section outlines the key web test case
scenarios, including functionality, usability, regression, end-to-end, cross-
browser, and performance testing.

Functional Testing
A single end-user can make the whole system crash in minutes, even after
unit, integration, and performance tests have passed. This usually happens
because the user does something the developers did not expect. The purpose
of functional testing is therefore to ensure that the functionality of the
software works as intended for an end-user. It tests this through the UI of
the application. As opposed to non-functional testing, it doesn’t deal with
the underlying source code, and doesn’t evaluate things like speed,
scalability, and reliability. There are many types of functional tests.
Examples of functional tests in a web application UI include testing that:
 The login to your web application is successful across browsers and
devices
 The web application is interacting as intended with external
databases and syncing successfully
 Invoices are being sent and received with the correct information and
securely
 Buttons, text fields, menus, etc., are working as per the requirements

Usability Testing
Usability testing focuses on design aspects rather than functional aspects,
assessing the user experience, and how intuitive and user-friendly the web
application is.
Key aspects include:
 User Interface Evaluation: Analyzing the layout, design, and navigability.
 User Experience Testing: Assessing the ease of learning and using the
application.
 Accessibility Testing: Ensuring the application is accessible to all
users, including those with disabilities.

Regression Testing
Regression testing is critical whenever updates or changes are made to the
application. It ensures that new code doesn't negatively impact existing
functionality, and typically includes functional tests as part of its scope.
This type of testing:
 Verifies Existing Functionality: Ensures that previous functions still
operate as intended after modifications.
 Identifies Unintended Consequences: Catches any new bugs
introduced by recent changes.
End-to-End Testing
End-to-end testing examines the complete functionality of the web
application from start to finish, emulating real user scenarios. It aims to
ensure that all components of the application work together seamlessly.
Panimalar Engineering College 6
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
End-to-end testing is typically applied to a business’ most important or
common business processes, to reduce the risk that these key flows break.
This involves:
 Workflow Testing: Ensuring all the integrated parts of the application
interact correctly.
 Data Integrity Testing: Confirming that data maintains its integrity
throughout all transactions.
Cross-Browser Testing
With the variety of browsers available, browser-based testing ensures that
the web application performs consistently across different browsers and
their versions. This testing type:
 Ensures Compatibility: Verifies that the application functions
correctly on various browsers.
 Identifies Browser-Specific Issues: Highlights any layout or functional
issues unique to certain browsers.
 Related reading: How to automate web testing across browsers and
devices

Performance Testing
Performance testing evaluates the web application’s stability and responsiveness
under various conditions. This includes:
 Load Testing: Assessing the application's ability to handle high volumes of
users.
 Stress Testing: Determining the application's breaking point and how
it recovers from failure.
 Speed Testing: Measuring response times and the speed of page
loading under normal conditions.

Web app test automation best practices


Before you start automating your web application tests, make sure you draft
a test automation strategy to keep you on track. Things to keep in mind
before you start automation are:
 What are the specific requirements of your web application?
 What types of tests do you need to automate?
 Which test automation tool best suits your requirements and goals,
as well as the resources on your team?
 How much maintenance will automation require?
As a first rule of thumb, start small, and once you’re comfortable, start
scaling your automation efforts. No one wants to end up with hundreds of
automated test cases that are impossible to maintain. Rather, think of
automation like a bell curve - automate too little, and the ROI on your
potential tool costs and onboarding will be too high. Automate too much,
and the time you spend on changing or maintaining your tests starts to
exceed the time saved. Ideally, find the sweet spot in the middle where
return is the highest.
Successful web application testing requires effective test automation
processes, clear communication within the team, an efficient strategy, and
an automation tool that doesn’t impair testers, but enables them.

Web Application Automated test tools:


The below described are the best tools for web application automated testing:
Katalon
Studio
Panimalar Engineering College 7
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
Advantages:
 It is convenient and accessible to different types of testers(inclusive
and exclusive of both programmings).
 It is flexible and easy to use with its quick, powerful features(robust).
 It also supports image-based testing, which is quite an enhanced and new
feature.
 It supports integration with Jenkins.
 It’s known for its hassle-free, customizable execution workflow.
 It can support web application automation, API Testing, Mobile Testing.
 It has built-in support for creating test cases, generating test scripts,
reporting results, recording actions. It is famous for its built-in
support for groovy(java) scripting languages.
 It can be integrated with CI/DevOps workflow and other tools.

Disadvantages:
It only supports groovy(java). So it is feasible for java users only.
It is not an open-source tool. It is closed source code, and it further
results in a small community.
There are some performance issues, like more interruption causing the device to
slow down.

Cucumber

Advantages:
 It is a collaborative tool based on behavior-driven development.
 It is an open-source automated software testing tool.
 It helps in writing acceptance tests for our web applications.
 It provides the amalgamation of both test documentation and its
specification(specs).
 It supports multi-languages like python,perl,ruby,.net etc.
Panimalar Engineering College 8
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
It is provided with cross-platform compatibility.
It can be integrated with DevOps tools like GIT, Jenkins, etc., for better
enhancement.
Disadvantages:
 Integration and its dependency on generating reports through
plugins can be challenging enough.
 Every time a new attribute or feature undergoes it, we have to ensure all
current steps
and validate them to see if they can be used.

Selenium

Advantages:
 It is the most versatile automated software testing tool.
 This tool is open-source and widely supports all languages and
frameworks.
 It comes with heavy library packages.
 It supports cross-browser automation, API automation, and database
automation.
 Testers can use it for regression, exploratory testing, and quick
reproduction of bugs.
 It can be beneficial in parallel test execution techniques.
 It is highly known for its flexibility with ease of implementation.
 Its integration with gauge automation framework, Galen framework,
lambda test, etc., is trending nowadays.

Disadvantages:
 Test Maintenance in selenium can become cumbersome and even
expensive sometimes.
 Selenium requires coding skills, if not exceptional but above average,
though.
 It is only supported for web applications, though.
 Technical support and its reliability can cause problems, though.
 Flaky tests can be a big problem as they generate false negatives and
false positives or vice versa.

5.3 SELENIUM: INTRODUCING WEB DRIVER AND WEB ELEMENTS


Panimalar Engineering College 9
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
5.3.1 Selenium Testing Tools
Selenium 3.0 offers three important tools, Selenium WebDriver, Selenium
Server, and Selenium IDE. Each of these tools provides features to create,
debug, and run tests on supported browsers and operating systems. Let's
explore each of them in detail.
1. Selenium WebDriver
Selenium WebDriver is the successor of Selenium RC (Remote Control),
which has been officially deprecated. Selenium WebDriver accepts
commands using the JSON-Wire protocol (also called Client API) and sends
them to a browser launched by the specific driver class (such as
ChromeDriver, FirefoxDriver, or IEDriver). This is implemented through a
browser- specific browser driver. It works with the following sequence:
1. The driver listens to the commands from Selenium
2. It converts these commands into the browser's native API
3. The driver takes the result of native commands and sends the result back

to Selenium.
We can use Selenium WebDriver to do the following:
 Create robust, browser-based regression automation
 Scale and distribute scripts across many browsers and platforms
 Create scripts in your favourite programming language.
2. Selenium Server
Selenium Server allows us to run tests on browser instances running
on remote machines and in parallel, thus spreading a load of testing across
several machines. We can create a Selenium Grid, where one server runs as
the Hub, managing a pool of Nodes. We can configure our tests to connect to
the Hub, which then obtains a node that is free and matches the browser we
need to run the tests. The hub has a list of nodes that provide access to
browser instances, and lets tests use these instances similarly to a load
balancer.
Selenium Grid enables us to execute tests in parallel on multiple
machines by managing different types of browsers, their versions, and
operating system configurations centrally.
3. Selenium IDE
Selenium IDE is a Firefox add-on that allows users to record, edit, debug,
Panimalar Engineering College 10
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
and play back tests captured in the Selenese format, which was introduced
in the Selenium Core version. It also provides us with the ability to convert
these tests into the Selenium RC or Selenium WebDriver format. We can use
Selenium IDE to do the following:
 Create quick and simple scripts using record and replay, or use
them in exploratory testing
 Create scripts to aid in automation-aided exploratory testing
 Create macros to perform repetitive tasks on Web pages

5.3.2 WebElements
A web page is composed of many different types of HTML elements, such as
links, textboxes, dropdown buttons, a body, labels, and forms. These are
called WebElements in the context of WebDriver. Together, these elements
on a web page will achieve the user functionality. For example, let's look at
the HTML code of the login page of a website:
<html>
<body>
<form id="loginForm">
<label>Enter Username: </label>
<input type="text" name="Username"/>
<label>Enter Password: </label>
<input type="password" name="Password"/>
<input type="submit"/>
</form>
<a href="forgotPassword.html">Forgot Password ?</a>
</body>
</html>
In the preceding HTML code, there are different types of WebElements, such
as <html>,
<body>, <form>, <label>, <input>, and <a>, which together make a web page
provide the Login feature for the user. Let's analyze the following WebElement:
<label>Enter Username: </label>
Here, <label> is the start tag of the WebElement label. Enter Username: is the
text present on the label element. Finally, </label> is the end tag, which
indicates the end of a WebElement. Similarly, take another WebElement:
<input type="text" name="Username"/>
In the preceding code, type and name are the attributes of the WebElement
input with the text and Username values, respectively.
UI-automation using Selenium is mostly about locating these
WebElements on a web page and executing user actions on them.

5.4 LOCATING WEB ELEMENTS


Let's start by automating the Search feature from the Homepage of the
demo application, http://amazon.in/, which involves navigating to the
homepage, typing the search text in the textbox, and executing the search.
The code is as follows:

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

public class SelTest {


public static void main(String[] args) throws InterruptedException {
Panimalar Engineering College 11
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
System.setProperty("webdriver.chrome.driver","C:
\\selenium webdriver\\chromedriver-
win64\\chromedriver.exe");
WebDriver driver=(WebDriver) new
ChromeDriver();
driver.get("https://www.amazon.in");
driver.manage().window().maximize();
Thread.sleep(4000);
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("app
le iphone"); Thread.sleep(4000);
WebElement subbtn = driver.findElement(By.id("nav-search-
submit- button"));
subbtn.click();
//driver.findElement(By.id("nav-search-submit-button")).click();
//driver.findElement(By.className("nav-
input")).click();
driver.findElement(By.linkText("Get It
Today")).click(); Thread.sleep(4000);
driver.navigate().to("https://www.coe.panimalar.a
c.in"); Thread.sleep(4000);
driver.navigate().back();
//System.out.println(driver.getTitle());
//System.out.println(driver.getPageS
ource()); Thread.sleep(4000);
driver.quit();
}
}

As you can see, there are three new things that are highlighted, as follows:
WebElement subbtn = driver.findElement(By.id("nav-search-submit-
button")); They are the findElement() method, the By.id() method, and the
WebElement interface. The findElement() and By() methods instruct
WebDriver to locate a WebElement on a web page, and once found, the
findElement() method returns the WebElement instance of that element.
Actions, such as click and type, are performed on a returned WebElement
using the methods declared in the WebElement interface.

The findElement method


In UI automation, locating an element is the first step before executing
any user actions on it. WebDriver's findElement() method is a convenient way
to locate an element on the web page. According to WebDriver's Javadoc, the
method declaration is as follows:
WebElement findElement(By by)
So, the input parameter for the findElement() method is the By instance.
The By instance is a WebElement-locating mechanism.
The return type of the findElement() method is the WebElement
instance that represents the actual HTML element or component of the web
page. The method returns the first WebElement that the driver comes across
that satisfies the locating-mechanism condition. This WebElement instance
will act as a handle to that component from then on.
Appropriate actions can be taken on that component by the test-
script developer using this returned WebElement instance. If WebDriver
doesn't find the element, it throws a runtime exception named
Panimalar Engineering College 12
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
NoSuchElementException, which the invoking class or method should
handle.

The findElements method


For finding multiple elements matching the same locator criteria on a web
page, the findElements() method can be used. It returns a list of
WebElements found for a given locating mechanism. The method declaration
of the findElements() method is as follows:
java.util.List findElements(By by)
The input parameter is the same as the findElement() method, which is an
instance of the By class. The difference lies in the return type. Here, if no
element is found, an empty list is returned and if there are multiple
WebElements present that satisfy the locating mechanism, all of them are
returned to the caller in a list.

Using the By locating mechanism


By is the locating mechanism passed to the findElement() method or the
findElements() method to fetch the respective WebElement(s) on a web
page. There are eight different locating mechanisms; that is, eight different
ways to identify an HTML element on a web page. They are located by ID,
Name, ClassName, TagName, LinkText, PartialLinkText,
XPath, and CSS Selector.
1. The By.id() method
consider the HTML code of the Search box:
<input id="search" type="search" name="q" value="" class="input-
textrequired- entry" maxlength="128" placeholder="Search entire store
here..." autocomplete="off">
In the preceding code, the id attribute value of the search
box is search. WebElement searchBox =
driver.findElement(By.id("search"));
In preceding code, we used the By.id() method and the search box's id
attribute value to find the element.
2. The By.name() method:
WebElement searchBox = driver.findElement(By.name("q"));

3. The By.className() method:


For instance, a style attribute for a button can be declared in a CSS file as
follows:
.buttonStyl
e{ width:
50px;
height:
50px;
border-radius: 50%;
margin: 0% 2%;
}
Now, this style can be applied to the button element in a web page as follows:
<button name="sampleBtnName" id="sampleBtnId"
class="buttonStyle">I'm
Button</button>
WebElement searchButton = driver.findElement(By.className("buttonStyle
"));

Panimalar Engineering College 13


21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
4. The By.linkText() method:
A typical anchor tag looks like this:
<a href="http://demo-
store.seleniumacademy.com/customer/account/" title="My
Account">My Account</a>
driver.findElement(By.linkText("My Account"));

5. The By.partialLinkText() method:


WebElement orderAndReturns =
driver.findElement(By.partialLinkText("My"));

6. The By.tagName() method


List<WebElement> links = driver.findElements(By.tagName("a"));

7. The By.xpath() method


WebDriver uses XPath to identify a WebElement on the web page. Before we
see how it does that, let's quickly look at the syntax for XPath. XPath is a
short name for the XML path, the query language used for searching XML
documents. The HTML for our web page is also one form of the XML
document. So, in order to identify an element on an HTML page, we need to
use a specific XPath syntax:
 The root element is identified as //.
 To identify all the div elements, the syntax will be //div.
 To identify the link tags that are within the div element, the syntax will be
//div/a.
 To identify all the elements with a tag, we use *. The syntax will be
//div/*.
 To identify all the div elements that are at three levels down from the root,
we can use
//*/*/div.
 To identify specific elements, we use attribute values of those
elements, such as
//*/div/a[@id='attrValue'], which will return the anchor element. This
element is at the third level from the root within a div element and has an
id value of attrValue.
So, we need to pass the XPath expression to the By.xpath locating
mechanism to make it identify our target element.
Now, let's see the code example and how WebDriver uses this XPath to
identify the element: WebElement searchBox =
driver.findElement(By.xpath("//*[@id='search']"));
searchBox.sendKeys("Bags");
searchBox.submit();

8. The By.cssSelector() method


The By.cssSelector() method is similar to the By.xpath() method in its usage, but
the difference
is that it is slightly faster than the By.xpath locating mechanism. The
following are the commonly used syntaxes to identify elements:
 To identify an element using the div element with the #flrs ID, we use the
#flrs syntax
 To identify the child anchor element, we use the #flrs > a syntax,
which will return the link element
Panimalar Engineering College 14
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
 To identify the anchor element with its attribute, we use the
#flrs > a[a[href="/intl/en/about.html"]] syntax
Let's try to modify the previous code, which uses the XPath locating
mechanism to use the cssSelector mechanism:
WebElement searchBox =
driver.findElement(By.cssSelector("#search"));

5.5 ACTIONS ON WEB ELEMENTS


Different WebElements will have different actions that can be taken
on them. For example, in a textbox element, we can type in some text or
clear the text that is already typed in it. Similarly, for a button, we can click
on it, get the dimensions of it, and so on, but we cannot type into a button,
and for a link, we cannot type into it.
So, though all the actions are listed in one WebElement interface, it is
the test script developer's responsibility to use the actions that are
supported by the target element. In case we try to execute the wrong action
on a WebElement, we don't see any exception or error thrown and we don't
see any action get executed; WebDriver ignores such actions silently.

5.5.1 Getting element properties and attributes


There are various methods to retrieve value and properties from the
WebElement interface.

1. The getAttribute() method


The getAttribute method can be executed on all the WebElements. The
HTML attributes are modifiers of HTML elements. They are generally key-
value pairs that appear in the start tag of an element. For example:
<label name="Username" id="uname">Enter Username: </label>
In the preceding code, name and id are the attributes or attribute keys and
Username and uname are the attribute values.
The API syntax of the getAttribute() method is as follows:
java.lang.String getAttribute(java.lang.String name)
In the preceding code, the input parameter is String, which is the name of
the attribute. The return type is again String, which is the value of the
attribute.
Now let's see how we can get all the attributes of a WebElement using
WebDriver. Here, we will make use of the Search box from the example
application. This is what the element looks like:
<input id="search" type="search" name="q" value=""
class="input-text required-entry" maxlength="128"
placeholder="Search entire store here..." autocomplete="off">
We will list all the attributes of this WebElement using WebDriver. The
code for that is as follows:
WebElement searchBox = driver.findElement(By.name("q"));
System.out.println("Name of the box is: " +
searchBox.getAttribute("name")); System.out.println("Id of the
box is: " +searchBox.getAttribute("id"));
System.out.println("Class of the box is: " +
searchBox.getAttribute("class"));
System.out.println("Placeholder of the box is: " +
searchBox.getAttribute("placeholder"));

In the preceding code, the last four lines of code use the getAttribute()
Panimalar Engineering College 15
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
method to fetch the attribute values of the name, id, class, and placeholder
attributes of the WebElement search box. The output of the preceding code
will be following:
Name of the box is: q
Id of the box is: search
Class of the box is: input-text required-
entry Placeholder of the box is: Search
entire store here...
Going back to the By.tagName() method of the previous section, if the
search by a locating mechanism, By.tagName, results in more than one
result, you can use the getAttribute() method to further filter the results and
get to your exact intended element.

2. The getText() method:


The getText method can be called from all the WebElements. It will return
visible text if the element contains any text on it, otherwise it will return
nothing. The API syntax for the getText() method is as follows:
java.lang.String getText()
There is no input parameter for the preceding method, but it returns
the visible innerText string of the WebElement if anything is available,
otherwise it will return an empty string. The following is the code to get the
text present on the Site notice element present on the example application
Homepage:
WebElement siteNotice = driver.findElement(By .className("global-
site-notice")); System.out.println("Complete text is: " +
siteNotice.getText());
The preceding code uses the getText() method to fetch the text present
on the Site notice element, which returns the following:
Complete text is: This is a demo store. Any orders placed through this
store will not be honored or fulfilled.

3. The getCssValue() method


The getCssValue method can be called on all the WebElements. This
method is used to fetch a CSS property value from a WebElement. CSS
properties can be fontfamily, background- color, color, and so on. This is
useful when you want to validate the CSS styles that are applied to your
WebElements through your test scripts.
System.out.println("Font of the box is: " +
searchBox.getCssValue("font-family")); The preceding code uses the
getCssValue() method to find font-family of the text visible in the Search
box. The output of the method is shown here:
Font of the box is: Raleway, "Helvetica Neue", Verdana, Arial, sans-serif

4.The getLocation() method


The getLocation method can be executed on all the WebElements. This is
used to get the relative position of an element where it is rendered on the
web page. This position is calculated relative to the top-left corner of the web
page of which the (x, y) coordinates are assumed to be (0, 0). This method
will be of use if your test script tries to validate the layout of your web page.
System.out.println("Location of the box is: " +
searchBox.getLocation());
The output for the preceding code is the (x, y) location of the Search box, as
shown in the following screenshot:
Panimalar Engineering College 16
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
Location of the box is: (873, 136)

5. The getSize() method


The getSize method can also be called on all the visible components of HTML.
It will return the width and height of the rendered WebElement.
The code for that is as follows:
System.out.println("Size of the box is: " + searchBox.getSize());
The output for the preceding code is the width and height of the Search box, as
shown in the following screenshot:
Size of the box is: (281, 40)
6.The getTagName() method
The getTagName method can be called from all the WebElements. This will
return the HTML tag name of the WebElement. For example, in the following
HTML code, the button is the tag name of the HTML element:
<button id="gbqfba" class="gbqfba" name="btnK" aria-
label="Google Search"> In the preceding code, the button is the tag
name of the HTML element.
The code for that is as follows:
WebElement searchButton =
driver.findElement(By.className("searchbutton"));
System.out.println("Html tag of the button is: " +
searchButton.getTagName());
The preceding code uses the getTagName() method to get the tag name of the
Search button element. The output of the code is as expected:
Html tag of the button is: button

5.5.2 Performing actions on WebElements


Let's explore the various methods available in the WebElement interface.
1. The sendKeys() method
The sendKeys action is applicable for textbox or textarea HTML elements.
This is used to type text into the textbox. This will simulate the user
keyboard and types text into WebElements exactly as a user would. The API
syntax for the sendKeys() method is as follows:
void sendKeys(java.lang.CharSequence...keysToSend)
The input parameter for the preceding method is CharSequence of text that
has to be entered into the element. This method doesn't return anything.
Now, let's see a code example of how to type a search text into the Search
box using the sendKeys() method:
WebElement searchBox =
driver.findElement(By.name("q"));
searchBox.sendKeys("Phones");
searchBox.submit();
In the preceding code, the sendKeys() method is used to type the required
text in the textbox element of the web page. This is how we deal with normal
keys, but if you want to type in some special keys, such as Backspace,
Enter, Tab, or Shift, we need to use a special enum class of WebDriver,
named Keys. Using the Keys enumeration, you can simulate many special
keys while typing into a WebElement.
Now let's see some code example, which uses the Shift key to type the
text in uppercase in the Search Box:
searchBox.sendKeys(Keys.chord(Keys.SHIFT,"phones"));
In the preceding code, the chord() method from the Keys enum is used to type
the key, while the text specified is being given as an input to be the textbox.
Panimalar Engineering College 17
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION

2. The clear() method


The clear action is similar to the sendKeys() method, which is applicable for
the textbox and textarea elements. This is used to erase the text entered in a
WebElement using the sendKeys() method. This can be achieved using the
Keys.BACK_SPACE enum, but WebDriver has given us an explicit method to
clear the text easily.
The code for that is as follows:
WebElement searchBox =
driver.findElement(By.name("q"));
searchBox.sendKeys(Keys.chord(Keys.SHIFT,"phon
es")); searchBox.clear();
We have used the WebElement's clear() method to clear the text after
typing phones into the Search box.

3. The submit() method


The submit() action can be taken on a Form or on an element, which is inside
a Form element. This is used to submit a form of a web page to the server
hosting the web application.
searchBox.submit();
5.5.3 Checking the WebElement state
There are methods to check whether the WebElement is displayed in the
Browser window, whether it is editable, and if the WebElement is Radio
Button of Checkbox, we can determine whether it's selected or unselected.
Let's see how we can use the methods available in the WebElement
interface.

1. The isDisplayed() method


The isDisplayed action verifies whether an element is displayed on the web
page and can be executed on all the WebElements. The API syntax for the
isDisplayed() method is as follows: boolean isDisplayed()
The preceding method returns a Boolean value specifying whether the target
element is displayed on the web page. The following is the code to verify
whether the Search box is displayed, which obviously should return true in
this case:
WebElement searchBox = driver.findElement(By.name("q"));
System.out.println("Search box is displayed: " + searchBox.isDisplayed());
The preceding code uses the isDisplayed() method to determine whether the
element is displayed on a web page. The preceding code returns true for the
Search box:
Search box is displayed: true

2. The isEnabled() method


The isEnabled action verifies whether an element is enabled on the web page
and can be executed on all the WebElements. The API syntax for the isEnabled()
method is as follows:
boolean isEnabled()
System.out.println("Search box is enabled: " + searchBox.isEnabled());

3. The isSelected() method


The isSelected method returns a boolean value if an element is selected on
the web page and can be executed only on a radio button, options in select,
and checkbox WebElements. When executed on other elements, it will return
Panimalar Engineering College 18
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
false.
System.out.println("Search box is selected: " + searchBox.isSelected());

5.6 DIFFERENT WEB DRIVERS


Let us explore the WebDriver implementation for Mozilla Firefox, Google
Chrome, Microsoft Internet Explorer, Microsoft Edge, and Safari. With
WebDriver becoming a W3C specification, all of the major browser vendors
now support WebDriver natively.

1. Firefox Driver
The new driver for Firefox is called Geckodriver. The Geckodriver
provides the HTTP API described by the W3C WebDriver Protocol to
communicate with Gecko browsers, such as Firefox. It translates calls into
the Firefox Remote Protocol (Marionette) by acting as a proxy between the
local and remote ends.
Using GeckoDriver:
First of all, we need to download the Geckodriver executable from
https://github.com/ mozilla/geckodriver/releases. Download the
appropriate version of Geckodriver based on the Firefox version installed on
your computer as well as the operating system. Copy the executable file into
the /src/test/resources/drivers folder.
Provide the path of the Geckodriver binary in the
webdriver.gecko.driver property, and instantiate the FirefoxDriver class:
WebDriver driver;
System.setProperty("webdriver.gecko.driver","./src/test/resources/drivers/
geckodriver
.exe");
driver = new FirefoxDriver();
driver.get("http://demo-store.seleniumacademy.com/");
Using Headless Mode
Headless mode is a very useful way to run Firefox for automated testing
with Selenium WebDriver. In headless mode, Firefox runs as normal only
you don't see the UI components. This makes Firefox faster and tests run
more efficiently, especially in the CI (Continuous Integration) environment.
We can run Selenium tests in headless mode by configuring the
FirefoxOptions class, as shown in the following code snippet:
WebDriver driver;
System.setProperty("webdriver.gecko.driver",
"./src/test/resources/drivers/geckodriver 2"); FirefoxOptions
firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);
driver = new FirefoxDriver(firefoxOptions);
During the execution, you will not see the Firefox window on the screen but
the test will be executed in headless mode.

2. Chrome Driver
The ChromeDriver works similar to the Geckodriver and implements
the W3C WebDriver protocol. First of all, we need to download the chrome
driver executable from https://chromedriver.chromium.org/downloads.
Download the appropriate version of chromedriver based on the Chrome
version installed on computer as well as the operating system. Copy the
executable file into the /src/test/resources/drivers folder.
Provide the path of the chromedriver binary in the
Panimalar Engineering College 19
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
webdriver.chrome.driver property, and instantiate the ChromeDriver class:
System.setProperty("webdriver.chrome.driver","C:\\seleniumwebdriver
\\chromedrive r-in64 \\chromedriver.exe");
WebDriver driver=(WebDriver) new
ChromeDriver();
driver.get("https://www.amazon.in");

Using Headless Mode


Similar to Firefox, we can run tests in headless mode with ChromeDriver.
This makes Chrome tests run faster and tests run more efficiently, especially
in the CI (Continuous Integration) environment.
We can run Selenium tests in headless mode by configuring the
ChromeOptions class as shown in the following code snippet:
WebDriver driver;
System.setProperty("webdriver.chrome.driver","./src/test/resources/drivers/c
hromedriver"); ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
driver = new ChromeDriver(chromeOptions);
driver.get("http://demo-
store.seleniumacademy.com/");

In the preceding code, we first created an instance of the ChromeOptions


class, called the setHeadless() method, that passes the value as true to
launch the Chrome browser in headless mode. During the execution, you
will not see the Chrome window on the screen but the test will be executed
in headless mode.

3. Internet Explorer Driver:


In order to execute your test scripts on the Internet Explorer browser, you
need WebDriver's InternetExplorerDriver. Similar to Google Chrome and
Firefox, we need to download the IEDriver Server executable from
https://www.seleniumhq.org/download/ for Internet Explorer.
The IEDriver server then uses its IEThreadExplorer class, which is
written in C++, to drive the IE browser using the Component Object Model
framework. The following is the code
that instantiates InternetExplorerDriver:
WebDriver driver;
System.setProperty("webdriver.ie.driver","./src/test/resources/drivers/IED
riverServer. exe");
driver = new InternetExplorerDriver();
driver.get("http://demo-
store.seleniumacademy.com/");

4. Edge Driver
Microsoft Edge is the latest web browser launched with Microsoft Windows
10. Microsoft Edge was one of the first browsers to implement the W3C
WebDriver standard and provides built-in support for Selenium WebDriver.
Similar to Internet Explorer, in order to execute test scripts on the
Microsoft Edge browser, we need to use the EdgeDriver class and a
standalone Microsoft WebDriver Server executable. The Microsoft WebDriver
Server is maintained by the Microsoft Edge development team. You can find
more information at https://docs.microsoft.com/en- gb/microsoft-
edge/webdrive.
Panimalar Engineering College 20
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
We need to download and install Microsoft WebDriver Server on
Windows 10 (https://developer.microsoft.com/en-us/microsoft-
edge/tools/webdriver/):
WebDriver driver;
System.setProperty("webdriver.edge.driver","./src/test/resources/drivers/
MicrosoftWe bDriver.exe");
EdgeOptions options = new
EdgeOptions();
options.setPageLoadStrategy("eager
"); driver = new
EdgeDriver(options);
driver.get("http://demo-store.seleniumacademy.com/");

5. Safari Driver
With Selenium 3.0 and WebDriver becoming the W3C standard, Apple now
provides SafariDriver built into the browser. We do not have to download it
separately. However, in order to work it with Selenium WebDriver, we have
to set a Develop | Allow Remote Automation option from Safari's main
menu. This is as straight forward. The following is the test script using the
Safari Driver:
WebDriver driver;
driver = new SafariDriver();
driver.get("http://demo-store.seleniumacademy.com/");

5.7 UNDERSTANDING WEB DRIVER EVENTS


Selenium WebDriver provides an API for tracking the various events that
happen when test scripts are executed using WebDriver. Many navigation
events get fired before and after a WebDriver internal event occurs (such as
before and after navigating to a URL, and before and after browser back-
navigation) and these can be tracked and captured. To throw an event,
WebDriver gives you a class named EventFiringWebDriver, and to catch that
event, it provides the test-script developer with an interface named
WebDriverEventListener. The test-script developer should provide its own
implementations for the overridden methods from the interface.

Introducing the eventFiringWebDriver and eventListener classes:


The EventFiringWebDriver class is a wrapper around the WebDriver that
gives the driver the capability to fire events. The EventListener class, on
the other hand, waits to listen to EventFiringWebDriver and handles all of
the events that are dispatched. There can be more than one listener waiting
to hear from the EventFiringWebDriver class for an event to fire. All of the
event listeners should be registered with the EventFiringWebDriver class to
get notified. The following flow diagram explains what has to be done to
capture all of the events

Panimalar Engineering College 21


21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
raised by EventFiringWebDriver during the execution of test cases:

Creating an instance of EventListener


The EventListener class handles all of the events that
are dispatched by the EventFiringWebDriver class. There
are two ways to create an EventListener class:
 By implementing the WebDriverEventListener interface.
 By extending the AbstractWebDriverEventListener class provided in
theWebDriver library.
It is up to you, as a test-script developer, to choose which way to go.

Implementing WebDriverEventListener
The WebDriverEventListener interface has all the event methods declared.
The EventFiringWebDriver class, as soon as it realizes an event has
occurred, invokes the registered method of WebDriverEventListener. Here,
we have created an IAmTheEventListener named class and have
implemented WebDriverEventListener.

Panimalar Engineering College 22


21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
Now we need to provide implementation for all the methods declared in it.
Currently,
in WebDriverEventListener, there are 15 methods.
Make sure the IDE provides us with the dummy implementation of
these methods. The class that we have created with all 15 overridden
methods is as follows (we have provided implementations for a couple of
methods as an example):
public class IAmTheEventListener implements
WebDriverEventListener { @Override
public void beforeAlertAccept(WebDriver webDriver) {
}
@Override
public void beforeAlertDismiss(WebDriver webDriver) {
}
….
….
@Overrid
e
public void beforeNavigateTo(String url, WebDriver
webDriver) { System.out.println("Before Navigate To " +
url);
}
@Override
public void afterNavigateTo(String s, WebDriver
webDriver) { System.out.println("Before Navigate
Back. Right now I'm at "
+ webDriver.getCurrentUrl());
}
}

Extending AbstractWebDriverEventListener
The second way to create a listener class is by extending the
AbstractWebDriverEventListener class. AbstractWebDriverEventListener is
an abstract class that implements WebDriverEventListener. Though it
doesn't really provide any implementation for the methods in the
WebDriverEventListener interface, it creates a dummy implementation such
that the listener class that you are creating doesn't have to contain all the
methods, only the ones that you, as a test-script developer, are interested
in. The following is a class we have created that extends
AbstractWebDriverEventListener and provides implementations for a couple
of methods in it. This way, we can override only the methods that we are
interested in rather than all of the methods in our class:
package com.example;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.support.events.AbstractWebDriverEventList
ener; public class IAmTheEventListener2 extends
AbstractWebDriverEventListener { @Override
public void beforeNavigateTo(String url, WebDriver
driver) { System.out.println("Before Navigate To "+
url);
}
@Override
Panimalar Engineering College 23
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
public void beforeNavigateBack(WebDriver driver) {
System.out.println("Before Navigate Back. Right now I'm at "
+ driver.getCurrentUrl());
}
}

Creating a WebDriver instance


Now that we have created our listener class that listens for all of the events
generated, it's time to create our test script class and let it call
IAmTheDriver.java. After the class is created, we declare a ChromeDriver
instance in it:
WebDriver driver = new ChromeDriver();
The ChromeDriver instance will be the underlying driver instance that
drives all the driver events.

Creating EventFiringWebDriver and EventListener instances


Now that we have the basic driver instance, pass it as an argument while
constructing the EventFiringWebDriver instance. We will be using this
instance of the driver to execute all of the further user actions.
Now, using the following code, instantiate the EventListener,
IAmTheEventListener.java, or IAmTheEventListener2.java class that we
created previously. This will be the class to which all of the events are
dispatched:
EventFiringWebDriver eventFiringDriver = new
EventFiringWebDriver(driver); IAmTheEventListener eventListener
= new IAmTheEventListener();

Registering EventListener with EventFiringWebDriver


For the event executions to be notified by EventListener, we have registered
EventListener to the EventFiringWebDriver class. Now the
EventFiringWebDriver class will know where to send the notifications. This
is done by the following line of code:
eventFiringDriver.register(eventListener);

Executing and verifying the events


Now it's time for our test script to execute events, such as navigation events.
Let's first navigate to Google and then Facebook. We will use the browser
back-navigation to go back to Google. The full code of the test script is as
follows:
public class IAmTheDriver {
public static void main(String... args){
System.setProperty("webdriver.chrome.
driver",
"./src/test/resources/drivers/chrome
driver"); WebDriver driver = new
ChromeDriver();
try {
EventFiringWebDriver
eventFiringDriver = new
EventFiringWebDriver(driver);
IAmTheEventListener eventListener = new
IAmTheEventListener();
eventFiringDriver.register(eventListener);
Panimalar Engineering College 24
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
eventFiringDriver.get("http://www.google.com");
eventFiringDriver.get("http://www.facebook.com");
eventFiringDriver.navigate().back();
} finally {
driver.close
();
driver.quit()
;
}
}
}
In the preceding code, we modify our listener class to record navigateTo and
navigateBack before and after events inherited from the
AbstractWebDriverEventListener class. The modified methods are as
follows:
@Override
public void beforeNavigateTo(String url, WebDriver
driver) { System.out.println("Before Navigate To: " +
url
+ " and Current url is: " + driver.getCurrentUrl());
}
@Override
public void afterNavigateTo(String url, WebDriver driver)
{
System.out.println("After Navigate To: " + url
+ " and Current url is: " + driver.getCurrentUrl());
}
@Override
public void beforeNavigateBack(WebDriver driver) {
System.out.println("Before Navigate Back. Right now I'm at " +
driver.getCurrentUrl());
}
@Override
public void afterNavigateBack(WebDriver driver) {
System.out.println("After Navigate Back. Right now I'm at " +
driver.getCurrentUrl());
}
Now if you execute your test script, the output will be as follows:
Before Navigate To: http://www.google.com and Current
url is: data:, After Navigate To: http://www.google.com
and Current url is:
https://www.google.com/?gws_rd=ssl
Before Navigate To: http://www.facebook.com and
Current url is: https://www.google.com/?gws_rd=ssl
After Navigate To: http://www.facebook.com and
Current url is: https://www.facebook.com/
Before Navigate Back. Right now I'm at https://www.facebook.com/
After Navigate Back. Right now I'm at https://www.google.com/?gws_rd=ssl

5.8 TESTNG

TestNG is an open-source automated testing framework; where NG means


Next Generation. TestNG can be used for unit, functional, integration and
Panimalar Engineering College 25
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
end to end testing. It is written in Java and it can be used in Java as well as
Java related languages such as groovy.

5.8.1 UNDERSTANDING TESTNG.XML

TestNG.xml file is a configuration file that helps in organizing our tests. It


allows testers to create and handle multiple test classes, define test suites
and tests.
It makes a tester’s job easier by controlling the execution of tests by
putting all the test cases together and run it under one XML file. This is a
beautiful concept, without which, it is difficult to work in TestNG.
Advantages Of TestNG.xml
 It provides parallel execution of test methods.
 It allows the dependency of one test method on another test method.
 It helps in prioritizing our test methods.
 It allows grouping of test methods into test groups.
 It supports the parameterization of test cases using @Parameters
annotation.
 It helps in Data-driven testing using @DataProvider annotation.
 It has different types of assertions that help in validating the expected
results with the actual results.
 It has different types of HTML reports, Extent reports, etc. for a
better and clear understanding of our test summary.
 It has listeners who help in creating logs.

Concepts Used in TestNG.xml

#1) A Suite is represented by one XML file. It can contain one or more tests
and is defined by the <suite> tag.
Example: <suite name=”Search Suite”>

#2) A Test is represented by <test> and can contain one or more


TestNG classes. Example: <test name=”Search Test”>

#3) A Class is a Java class that contains TestNG annotations. Here it is


represented by the
Panimalar Engineering College 26
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
<class> tag and can contain one or more
test methods. Example:
<classes>
<class name="com.example.SearchTest"/>
</classes>

TestNG.xml Example:

<?xml version="1.0" encoding="UTF-8"?>


<suite parallel="false" name="Test Suite">
<test name="Test">
<classes>
<class name="com.example.SearchTest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite --
>

#4) A Test method is a Java method annotated by @Test methods in the source
file.

package com.example;

import org.testng.annotations.Test;
import
org.testng.annotations.BeforeMethod
; import org.openqa.selenium.By;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDrive
r; import org.testng.Assert;
import org.testng.annotations.AfterMethod;
public class
SearchTest {
WebDriver
driver;

@BeforeMethod
public void setup()
{
System.setProperty("webdriver.chrome.driver","C:
\\selenium webdriver\\chromedriver-
win64\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://demo-store.seleniumacademy.com/");
}
@Test

Panimalar Engineering College 27


21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
public void searchProduct() {
// find search box and enter search string
WebElement searchBox =
driver.findElement(By.name("q"));
searchBox.sendKeys("Phones");
WebElement searchButton =
driver.findElement(By.className("search-
button")); searchButton.click();
Assert.assertEquals(driver.getTitle(), "Search results for: 'Phones'");
}

@AfterMethod
public void
tearDown() {
driver.quit();
}
}

#5) Run the test by right clicking on the TestNG xml file and select Run As -
> TestNG Suite. Once the testng.xml file has run, we can see the test
reports in the console as shown below:
===============================================
Suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

5.8.2 ADDING CLASSES, PACKAGES, METHODS TO TEST


TestNG provides multiple options for running test cases. Before going ahead
with creation of test with classes packages and methods, we will need a
sample project for defining test suites for execution.

Sample Project:
a. Open Eclipse.
b. create a project MutiTest .
c. In MultiTest create a package firstpackage.
d. In firstpackage create a class

FirstTestClass.java Add the following piece of

code in FirstTestClass.java: public class

FirstTestClass {

private final String firstTest = “My First


Test”; private final String secondTest = “My
Second Test”;

@Test
public void firstTest(){
System.out.println(firstTest);
Panimalar Engineering College 28
21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
assertEquals("My First Test",
firstTest);
}

@Test
public void secondTest(){
System.out.println(secondTest);
assertEquals("My Second Test",
secondTest);
}
}

1. Adding Packages:
Using 'Package' configuration option TestNG will execute all the test inside
specified Package. Let us add packages to the test suite.

1. Open the package “firstPackage” in “MultiTest” peoject.


2. Add new file TestNG configuration XML by name “testng.xml”to the project.
3. Add the following content to the testng.xml file:
<suite name="Package Suite" verbose="1">
<test name="Package Test">
<packages>
<package name="test.firstpackage" />
</packages>
</test>
</suite>

Output:
Running the proceeding xml file will give
output: “My First Test”
“My Second Test”
===============================================
Suite
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================
Now we have successfully executed TestNG test Suite by adding test packages
to the suite.

2. Adding Classes:
Using 'Class' configuration option TestNG enables us to run only specified
class name along with its package name. Let us add specified class/classes to
the test suite.

1. Open the package “firstPackage” in “MultiTest” peoject.


2. Add new file TestNG configuration XML by name “testing.xml”to the project.
3. Add the following content to the testng.xml file:
<suite name="Class Suite" verbose="1">
<test name="Test">
<classes>
<class name="test.firstpackage.FirstTestClass" />
</classes>

Panimalar Engineering College 29


21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION

</test>
</suit
e> Output:
Running the proceeding Xml file will output:
“My First Test”
“My Second
Test”
===============================================
Suite
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================
Now we have successfully executed TestNG test Suite by adding class to a
test. Similarly, we can add multiple classes by adding required number of
Class tags in xml file.

3. Adding Methods:
Using this option TestNG enables us to run only specified method in a
test class.

1. Open the package “firstPackage” in “MultiTest” peoject.


2. Add new file TestNG configuration XML by name “testing.xml”to the project.
3. Add the following content to the testng.xml file:
<suite name="Method Suite" verbose="1">
<test name="Method Test">
<classes>
<class name="test.firstpackage.FirstTestClass">
<methods>
<include name="secondTest" />
</methods>
</class>
</classes>
</test>
</suit
e> Output:
Running the proceeding Xml file will
output: “My Second Test”
===============================================
Suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

Now we have successfully executed TestNG test Suite by adding method to a


test.

5.8.3 TEST REPORTS

Reporting is the most important part of any test execution, as it helps the
user understand the result of the test execution, point of failure, and the
reasons for failure. Logging, on the other hand, is important to keep an eye
on the execution flow or for debugging in case of any failures. TestNG, by
default, generates a different type of report for its test execution. This
includes an HTML and an XML report output. TestNG also allows its users
to write their own reporter and use it with TestNG. There is also an option to

Panimalar Engineering College 30


21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION
write your own loggers, which are
notified at runtime by TestNG.
There are two ways to generate a report with TestNG −
Listeners − For implementing a listener class, the class has to implement
the org.testng.ITestListener interface. These classes are notified at runtime
by TestNG when the test starts, finishes, fails, skips, or passes.

Reporters − For implementing a reporting class, the class has to implement


an org.testng.IReporter interface. These classes are called when the whole
suite run ends. The object containing the information of the whole test run
is passed to this class when called.
Example:
Reporter.log("Browser Opened");
Reporter.log("Application started");

TestNG - HTML and XML Reports


After running testNG.xml file, go to the ./test-output folder. Open the
index.html on your default web browser. You will see the following HTML
report:

Similarly open the emailable-report.html file to view another html report:

Panimalar Engineering College 31


21IT1904 UNIT-V SOFTWARE TESTING AND AUTOMATION

Now, open the file ./test-output/testing-results.xml in the default XML editor


on your system, and you will see the following content in the XML file.

Reporter Log can be found in testing-results.xml as shown below:

Panimalar Engineering College 32

You might also like