CCS366-Software Testing and Automation-Lab-Manual

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

lOMoAR cPSD| 7367891

M.A.M. SCHOOL OF ENGINEERING


SIRUGANUR, TRICHY - 621 105.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

CCS366 – SOFTWARE TESTING AND AUTOMATION LABORATORY

Name :………………………..

Register Number :………………………..

Year/Semester :………………………..

Degree/Dept. :………………………..
lOMoAR cPSD| 7367891

M.A.M. SCHOOL OF ENGINEERING


SIRUGANUR, TRICHY- 621 105.
BONAFIDE CERTIFICATE

Certified that this is the bonafide record of work done by


Mr./Ms…………………….(Reg.No. ………………….) studying in Third
year fifth semester B.Tech. Artificial Intelligence and Data Science has
completed CCS366 – SOFTWARE TESTING AND AUTOMATION
LABORATORY during the academic year 2024-2025 successfully.

STAFF-IN-CHARGE HEAD OF THE DEPARTMENT

Submitted for the University Practical Examination held on…………. at


M.A.M. School of Engineering, Trichy- 621 105.

INTERNAL EXAMINER EXTERNAL EXAMINER

INDEX
lOMoAR cPSD| 7367891

EX.NO DATE NAME OF THE EXPERIMENT PAGE NO MARKS SIGN

1. Develop the test plan for testing an e-commerce


web/mobile application (www.amazon.in).

2. Design the test cases for testing the e-commerce


application

3. Test the e-commerce application and report the


defects in it.

4. Develop the test plan and design the test cases for an
inventory control system

5. Execute the test cases against a client server or


desktop application and identify the defects.
6. Test the performance of the e-commerce application.

7. Automate the testing of e-commerce applications


using Selenium.
8. Integrate TestNG with the above test automation.
9. Build a data-driven framework using Selenium and
TestNG
10. Build Page object Model using Selenium and
TestNG
11. Build BDD framework with Selenium, TestNG and
Cucumber
lOMoAR cPSD| 7367891

M.A.M. SCHOOL OF ENGINEERING, SIRUGANUR, TRICHY-621105


(Approved by AICTE, New Delhi and Affiliated to Anna University, Chennai)
(ACCREDITED BY NAAC)

VISION
“To emerge as a Premier Institute by empowering the students with competent knowledge, employable
skills and research culture to satisfy the needs of the industry and society”

MISSION
 To offer conducive and innovative teaching learning environment.
 To equip the students with value and ethical based training to enhance the employability skills.
 To promote continuous learning and to facilitate exchange of innovative ideas through industry
and institute collaborations.
 To imbibe communication skills, leadership skills, entrepreneurial skills and human values among
the student.
lOMoAR cPSD| 7367891

DEPARTMENT VISION

To build an ecosystem to contribute to society by producing leaders in Artificial


Intelligence and Data Science through education and research..

DEPARTMENT MISSION

 Train the students in the state-of-the-art technologies of AI&DS.


 Sensitize students to solve societal issues through AI techniques by inculcating values and ethics.
 Enhance employability and entrepreneurial skills in the field of AI & DS through experiential and
self-directed learning.
 Foster research aptitude among the students through project-based learning..

PROGRAM EDUCATIONAL OBJECTIVES (PEO’S)


Graduates can
 Utilize their proficiencies in the fundamental knowledge of basic sciences, mathematics, Artificial
Intelligence, data science and statistics to build systems that require management and analysis of
large volumes of data.
 Advance their technical skills to pursue pioneering research in the field of AI and Data Science
and create disruptive and sustainable solutions for the welfare of ecosystems.
 Think logically, pursue lifelong learning and collaborate with an ethical attitude in a
multidisciplinary team.
 Design and model AI based solutions to critical problem domains in the real world.
 Exhibit innovative thoughts and creative ideas for effective contribution towards economy
building.

PROGRAM SPECIFIC OUTCOMES (PSO’S)


The students will be able to
 Evolve AI based efficient domain specific processes for effective decision making in several
domains such as business and governance domains.
 Arrive at actionable Foresight, Insight, hindsight from data for solving business and engineering
problems
 Create, select and apply the theoretical knowledge of AI and Data Analytics along with practical
industrial tools and techniques to manage and solve wicked societal problems
 Develop data analytics and data visualization skills, skills pertaining to knowledge acquisition,
knowledge representation and knowledge engineering, and hence be capable of coordinating
complex projects.
 Able to carry out fundamental research to cater the critical needs of the society through cutting
edge technologies of AI.
lOMoAR cPSD| 7367891

PROGRAM OUTCOMES

Engineering Graduates will be able to:

1. Engineering knowledge: (K3) Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

2. Problem analysis: (K4) Identify, formulate, review research literature, and analysis complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

3. Design/development of solutions: (K4) Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

4. Conduct investigations of complex problems: (K5) Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

5. Modern tool usage: (K3, K5, K6) Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

6. The engineer and society: (A3) Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

7. Environment and sustainability: (A2) Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

8. Ethics: (A3) Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

9. Individual and team work: (A3) Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.

10. Communication: (A3) Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

11. Project management and finance: (A3) Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: (A2) recognize the need for and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
lOMoAR cPSD| 7367891

SYLLABUS

CCS366 SOFTWARE TESTING AND AUTOMATION LABORATORY


COURSE OBJECTIVES:
• To understand the basics of software testing
• To learn how to do the testing and planning effectively
• To build test cases and execute them
• To focus on wide aspects of testing and understanding multiple facets of testing
• To get an insight about test automation and the tools used for test automation

PRACTICAL EXERCISES: 30 PERIODS


1. Develop the test plan for testing an e-commerce web/mobile application
(www.amazon.in).
2. Design the test cases for testing the e-commerce application
3. Test the e-commerce application and report the defects in it.
4. Develop the test plan and design the test cases for an inventory control system.
5. Execute the test cases against a client server or desktop application and identify the
defects.
6. Test the performance of the e-commerce application.
7. Automate the testing of e-commerce applications using Selenium.
8. Integrate TestNG with the above test automation.
9. Mini Project:
a) Build a data-driven framework using Selenium and TestNG
b) Build Page object Model using Selenium and TestNG
c) Build BDD framework with Selenium, TestNG and Cucumber

COURSE OUTCOMES:
CO1: Understand the basic concepts of software testing and the need for software testing
CO2: Design Test planning and different activities involved in test planning
CO3: Design effective test cases that can uncover critical defects in the application
CO4: Carry out advanced types of testing
CO5: Automate the software testing using Selenium and TestNGs

TOTAL : 60 PERIODS
lOMoAR cPSD| 7367891

Ex.no : 01
Date : Develop the test plan for testing an e-commerce web/mobile application
(www.amazon.in).

Aim :
To Develop the test plan for testing an e-commerce web/mobile application
(www.amazon.in).

Test plan :

Scope
The scope of this test plan includes testing the core functionalities of the e-commerce application,
such as browsing products, adding items to the cart, placing orders, and managing user accounts. It
also covers testing across different platforms, including web and mobile.

Test Objectives
1) Validate the functionality of the e-commerce application.
2) Verify that the application is user-friendly and provides a smooth shopping experience.
3) Ensure that the application is secure and protects user data.
4) Test the application's compatibility across different browsers and devices.
5) Evaluate the performance and scalability of the application under various load conditions.
6) Identify and report any defects or issues found during testing.

Test Environment
1) Web browsers: Chrome, Firefox, Safari, and Edge.
2) Mobile devices: iOS and Android.
3) Test management tool: Jira or any other preferred tool.
4) Test automation tool: Selenium WebDriver or any other preferred tool.
5) Load testing tool: JMeter or any other preferred tool.

Test Approach
1) Requirements Analysis:
 Review the functional and non-functional requirements of the e-commerce application.
 Identify testable features and prioritize them based on criticality.

2) Test Design:
 Create test scenarios and test cases for each identified feature.
 Include positive and negative test cases to cover different scenarios.
 Define test data and test environment setup requirements.

3) Test Execution:
 Execute test cases manually or using test automation tools.
 Log defects in the test management tool and track their status.
 Perform regression testing after each bug fix or application update.

4) Performance Testing:
 Design and execute performance tests to evaluate the application's response time, throughput,
and scalability.
lOMoAR cPSD| 7367891

 Simulate different user loads and monitor system resources during testing.
 Identify performance bottlenecks and suggest improvements if needed.

5) Security Testing:
 Conduct security testing to identify vulnerabilities and ensure the application protects user
data.
 Test for common security issues like SQL injection, cross-site scripting (XSS), and
authentication vulnerabilities.
 Implement security best practices and follow industry standards.

6) Compatibility Testing:
 Test the application on different browsers, versions, and mobile devices.
 Verify that the application renders correctly and functions as expected across various
platforms.

Test Deliverables
1) Test plan document.
2) Test scenarios and test cases.
3) Test execution reports.
4) Defect reports with severity and priority.
5) Performance test reports.
6) Security test reports.

Result :
Thus the Test Plan for Testing an E-commerce Web/Mobile Application, the goal is to ensure
that the application functions as intended, meets user requirements, and provides a seamless
shopping experience.
lOMoAR cPSD| 7367891

Ex.no : 02
Date : Design the test cases for testing the e-commerce application

Aim :
To Design the test cases for testing the e-commerce application

Types of Ecommerce Testing :

Ecommerce websites function like any other web/mobile website. Hence it undergoes various types
of testing, such as:
 Functional Testing: If the tester wants to check if the checkout feature is working on the
website and scoped only to that feature, it is called functional testing.
 Usability Testing: When a customer wants to buy an item, searching, adding to the cart, and
making payment should be simple and easy. This is where usability testing kicks in.
 Performance Testing: When a single user is trying to access an ecommerce website, then it
should be extremely responsive.
 Mobile Application Testing: As there is a lot of penetration into the mobile space, many
users access the e-commerce websites on mobiles, So the website must have a good user
experience across different mobile.

General Ecommerce Test Cases


1. The user should be able to navigate to all the pages in the website
2. There should be a fallback page for any page load errors
3. Verify that all the links and banners work properly
4. Search results should be displayed with the most relevant item being shown first
5. All data related to the product – title, price, images, and description are all visible clearly
6. Maintain a session for each user and test verify the session times out after a while.

Login/Registration test cases for Online Shopping Website

 Test for valid username and password


 Test ―Forgot Password‖ and Reset Password functionality
lOMoAR cPSD| 7367891

 Validate If user is registered or not, and if not, provide an option to create an account
 Show Login screen by default for registered user
 Test that all fields are mandatory

Seller Product Creation Test Cases


For sellers who want to create their catalog, they should be able to add their products, and this flow
should be tested.
 Test that authenticated sellers can access authorized product creation panels under authorized
categories.
 Test the maximum product creation limit to avoid adding more products to the catalog.
 Test that seller‘s products are visible after some time
 Test the product creation process is working fine for the seller
 Test that there are no duplicate products
 Search Bar Test Cases for Online Shopping Website.

Search Bar Test Cases for Online Shopping Website

 Test what parameters the search is based on – for example, product name, brand name,
category, etc.
 Test if the search results are relevant
 Number of results to be displayed per page
 Test whether the search API is being called at every keystroke. (This isn‘t recommended, as
it would unnecessarily cause multiple API calls to the database)

Filter Results

 Test if the user can filter based on all the parameters on the page
lOMoAR cPSD| 7367891

 The user should be able to see results with default search criteria when at least one of the
filter parameters isn‘t mandatory
 Validation messages for invalid filter criteria
 When at least one filter criteria are required, and the user selects none, proper error messages
are shown

Product Detail Test Cases

 Test that all the product details are displayed correctly and that no empty/invalid details are
displayed.
 Product Images should be optimized for size and dimensions, which further helps in
performance testing.
 All the links(size, Pincode check, etc) about the product should be functional.

Shopping Cart

 Test that all items are added into the cart


 Test that all added items have at least a quantity, price, and delete option associated with it
 Test that the user can increase/decrease the quantity from the cart
 If a user adds the same item to the cart the amount of that item should increase in the cart
 On closing the tab/leaving the site, the items should still be in the cart upon returning to the
website.
lOMoAR cPSD| 7367891

Checkout Page

 User should be able to add coupons


 User should be shown the total amount with the necessary breakup as applicable.
 User should be able to select the desired payment method
 On adding more items or increasing/decreasing quantity, the total should change accordingly
 Calculate shipping costs based on shipping methods
 Right address should be selected and the user should be able to edit/add the address

Payments

 Perform security testing if in case the user‘s credit card details need to be saved
 For returning customers, they should be redirected to log in for checkout
 User should be logged out after the session times out
 Emails/test confirmation when the order is confirmed
lOMoAR cPSD| 7367891

Result :
Thus the eCommerce website has many more tests or features, and testing each is very time-
consuming and requires effort.
lOMoAR cPSD| 7367891

Ex.no : 03
Date : Test the e-commerce application and report the defects in it.

Aim :
To test the e-commerce application and report the defects in it.

Testing E-Commerce Websites

E-commerce applications/sites include web applications and mobile applications too. So, they
undergo all the typical test types.
 Functional Testing
 Usability Testing
 Security Testing
 Performance Testing
 Database Testing
 Mobile Application Testing
 A/B testing.

E-Commerce Testing Checklist

We have listed important segments and test cases for eCommerce website testing below.
 Home Page: Test that the correct text and images show up, whether static or dynamic. Links
to important pages (catalog, account login, cart) should also be visible and functional.
 Search and Navigation: Users should be able to search for relevant terms and be directed to
the exact page they are looking for. They should also be able to navigate to important
sections (product categories, cart, account info, etc.) with a couple of clicks. Test to check for
any bugs that may prevent a frictionless experience in this regard. Let‘s take the example of
the Amazon India website.

 Catalog of products and services: All products and services should be listed clearly, with
adequate descriptions and explanatory images. Images should be easy to magnify, and the
Add To Cart option should be upfront and seamlessly responsive.
lOMoAR cPSD| 7367891

 Order processing mechanism: Once orders are placed, products and their details must
match what the user selected. They should be able to choose a preferred shipping method,
and their addresses should be correctly mapped to the order. Additionally, return and
exchange policies should be accessible for reading before placing an order.

Payment Function/User Data: At this point, a number of variables need to be tested:


a) The privacy, security, and accuracy of customer data. This is where security testing comes in.
b) Required validations: First and last name, card number, CSV, OTP, etc.
c) Currency conversion (if the purchase is made in a foreign currency, does it convert correctly
to local currency?)
d) Can payment be canceled within a specific time frame?
e) Can customers pay in installments?
f) Generation of order confirmation and receipt
g) Is the site flawlessly and securely integrated with an external payment system? Does the
system work every time? What happens to the money if it is debited but the payment fails?

Defects of eCommerce Testing

1. Often, eCommerce websites use content management systems like Shopify, Woocommerce
to build the site in the shortest possible time.
2. However, these platforms offer integration with third-party services for various purposes –
gift cards, social media features, online payment management, etc.
3. However, too many third-party integrations increase testing effort, as each of them needs to
seamlessly and securely communicate and interact with the site.
4. With new devices and browser versions coming into existence as fast as you can blink,
eCommerce website testing must keep up.
lOMoAR cPSD| 7367891

Result
Thus Test the e-commerce application and report the defects in it was tested done and
verified successfully.
lOMoAR cPSD| 7367891

Ex.no : 04 Develop the test plan and design the test cases for an inventory control
Date : system.

Aim :
To Develop the test plan and design the test cases for an inventory control system.

Key steps to create an inventory management system

1) Engineer requirements and design an inventory system.


2) Plan the project in detail.
3) Develop inventory software and run QA.
4) Integrate the software with other systems.
5) Migrate inventory data.
6) Deploy the inventory system.
7) Conduct user training.
8) Ensure after-launch support.

Test Cases for Inventory Management System


lOMoAR cPSD| 7367891

Result
Thus the test plan and design the test cases for an inventory control system was done and
verified successfully.
lOMoAR cPSD| 7367891

Ex.no : 05 Execute the test cases against a client server or desktop application and
Date : identify the defects.

Aim :
To Execute the test cases against a client server or desktop application and identify the
defects.

Client Server Testing

Client-server testing is a software testing methodology focused on evaluating the


performance, functionality, and reliability of applications and systems built on a client-server
architecture.

Types Of Testing to Perform in Client-Server Test

Performing a comprehensive range of testing types is essential in client-server testing to


ensure the reliability, performance, and security of systems. Here are the primary types of
testing to consider:

Functional Testing
 Unit Testing: Evaluate individual client and server components to verify that they perform
their specific functions correctly.
 Integration Testing: Assess how well client and server components integrate and work
together, ensuring that data is exchanged accurately.
 System Testing: Conduct end-to-end testing to validate that the entire client-server system
functions as expected in real-world scenarios.

Performance Testing
 Load Testing: Measure the system‘s response and behavior under varying levels of user load
to identify performance bottlenecks.
 Stress Testing: Push the system beyond its intended capacity to determine breaking points
and assess its ability to recover.
 Scalability Testing: Evaluate how well the system scales to accommodate growing numbers
of clients or data transactions while maintaining performance.

Security Testing
 Authentication Testing: Verify that the authentication mechanisms (e.g., username/password,
tokens) work correctly and securely.
 Authorization Testing: Ensure that users can only access resources and functionalities they
are permitted to, and unauthorized access is prevented.
 Encryption Testing: Confirm that data transmission between the client and server is properly
encrypted to protect sensitive information.

Client-Server Testing Techniques

Manual Testing and Its Types

Manual testing is a fundamental testing approach where human testers execute test cases without
lOMoAR cPSD| 7367891

the use of automation tools or scripts.


 Functional Testing
 Usability Testing
 Exploratory Testing

Automated Testing
Automated testing involves the use of specialized tools and scripts to perform testing tasks
automatically. It is especially valuable for repetitive or complex test scenarios.

Black-Box Testing
Black-box testing focuses on evaluating an application‘s functionality without knowledge of
its internal code or structure. Testers interact with the application‘s interface and assess how
it responds to different inputs and conditions.

White-Box Testing
White-box testing is an approach where testers have access to the internal code and structure
of the application. They design tests to evaluate the correctness of the code, its logic, and the
execution paths within the application.

Mocking and Simulation


Mocking and simulation involve creating simulated or mock components to mimic the
behavior of real components or services that an application relies on.

Tools for Client-Server Testing :


Here are a few essential tools commonly used for client-server testing, along with a brief
explanation of how each tool aids in the testing process.

Testsigma

Testsigma, as an intelligent test automation platform for web and mobile applications, offers
significant advantages for automating client-server testing. With its no-code, scriptless automation
approach, Testsigma simplifies the test automation process, making it accessible to both technical
and non-technical team members.
lOMoAR cPSD| 7367891

Selenium

Selenium is a popular open-source automation testing tool primarily used for web applications. It
enables testers to automate interactions with web-based client applications, making it invaluable for
client-side testing.

JMeter

Apache JMeter is a versatile open-source tool designed for load testing, stress testing, and
performance testing of web applications and servers. JMeter helps assess how the server component
of a client-server application performs under various loads and concurrent user connections.

Wireshark

Wireshark is a widely used open-source network protocol analyzer that aids in network monitoring
and troubleshooting. For client-server testing, Wireshark is instrumental in capturing and analyzing
network traffic between the client and server components.
lOMoAR cPSD| 7367891

SoapUI

SoapUI is an open-source tool designed specifically for testing web services, making it suitable for
client-server applications that rely on RESTful APIs or SOAP-based services. With SoapUI, testers
can create and execute functional and load tests for the server-side components of client-server
applications.

Executing test cases and identifying defects:

 Use a checklist: A checklist can help you to make sure that you execute all of the test cases
and that you don't miss any important steps.
 Take your time: Don't rush through the test cases. Take your time to carefully follow the
instructions and to identify any defects.
 Be thorough: Don't just test the happy path. Test all of the different scenarios, including error
conditions and edge cases.
 Use a bug tracking system: A bug tracking system can help you to keep track of the defects
you find and to communicate with the developers.
lOMoAR cPSD| 7367891

Result
Thus the client-server testing is a critical process in ensuring the functionality, performance,
and security of applications operating on this architecture.
lOMoAR cPSD| 7367891

Ex.no : 06
Date : Test the performance of the e-commerce application

Aim :
To Test the performance of the e-commerce application.

Procedures / Performance testing :

Goals of eCommerce Performance Testing

 Reduce Risks: Many times, making major and considerable changes to a site can cause
notable strategic changes or even trigger significant losses.
 Increase Conversion Rates: By testing every aspect of an application and ensuring a smooth
visitor experience through site optimization, the application conversion rate is bound to
increase.
 Improve User Engagement: Testing tells which page element or process affects a user‘s
onsite journey and helps in rectifying the issues faster. The better the user experience, the
greater the onsite engagement.

Benefits of eCommerce Application Performance Testing

 Coupon codes or gift vouchers are provided to increase product sales and performance tests
ensure that coupon codes work well when applied to users in bulk.
 Multiple systems like email servers, social network sites, and enterprise content management
systems are involved in the backend and the performance test ensures flawless functioning of
various features like product images/videos, and social media in such an integrated system.
 eCommerce applications usually have more users than any other application and validation of
users is a must to filter out genuine customers. Performance test helps in validating multiple
sign-up and invoice email notifications in parallel.

Common Performance Testing Issues

 Slow DB server: Database size increases with the increase in product items of all ages, so
ensure to optimize DB queries.
 Faster Integrated Systems Communication: Multiple systems like email servers, social media
accounts, and payment channels are involved in the functioning of an eCommerce application
to ensure that integrated systems work well under a heavy load.
 System Scaling: Brands cannot predict user load during peak hours, hence, the need of the
hour is to be ready with tested scalable systems.

Main Features to be Tested in eCommerce Applications

 Searching For a Product: eCommerce sites provide various search filters to make the search
experience faster, which include price range, product type, country, and age. Hence, ensure
that searching for a product among billions of records does not halt the system and return the
expected records.
lOMoAR cPSD| 7367891

 Virtual Reality: Modern eCommerce sites provide advanced-level features to visualize


products. Online shoppers can now see how they would look wearing an item virtually.
Hence, we need to ensure the smooth movement of virtual images for a better experience.
 Testing Payment Gateway Integration: Failed transactions are one of the main reasons why
most customers exit an application without completing the purchase. So it's important to
ensure the proper functioning of payment gateways.
 Product Details Page: A fast product listing is important because every consumer will be
attracted to the product by how it's presented and how it's visible to them.

Result
Thus the Test the performance of the e-commerce application was done and verified
successfully.
lOMoAR cPSD| 7367891

Ex.no : 07
Date : Automate the testing of e-commerce applications using Selenium.

Aim :
To automate the testing of e-commerce applications using Selenium.

Procedures :

Positive scenario :
Automate the 'User Registration and Login' of Amazon like an e-commerce website

1. Test Case - Automate the User Registration process of an e-commerce website.

Steps to Automate:
i. Open this URL http://automationpractice.com/index.php
ii. Click on the sign-in link.
iii. Enter your email address in the 'Create and Account' section.
iv. Click on Create an Account button.
v. Enter your Personal Information, Address, and Contact info.
vi. Click on the Register button.
vii. Validate that the user is created.

Selenium code for User Registration:

This code is contributed by Uday. We have provided the code for only positive scenarios, you
should try automating negative scenarios yourself.

Code :

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import io.github.bonigarcia.wdm.WebDriverManager;
public class EcomSignUp {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver=new ChromeDriver();
String URL="http://automationpractice.com/index.php";
driver.get(URL);
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
driver.manage().window().maximize();
//Click on Sign in
driver.findElement(By.linkText("Sign in")).click();
//Enter email address
lOMoAR cPSD| 7367891

driver.findElement(By.cssSelector("[name='email_create']")).sendKeys("[email protected]"
);
//Click on "Create an account"
driver.findElement(By.xpath("//button[@name=\"SubmitCreate\"]")).click();
//Select Title
driver.findElement(By.xpath("//input[@id=\"id_gender1\"]")).click();
driver.findElement(By.name("customer_firstname")).sendKeys("Test User");
driver.findElement(By.name("customer_lastname")).sendKeys("Vsoft");
driver.findElement(By.id("passwd")).sendKeys("PKR@PKR");
// Enter your address
driver.findElement(By.id("firstname")).sendKeys("Test User");
driver.findElement(By.id("lastname")).sendKeys("Vsoft");
driver.findElement(By.id("company")).sendKeys("Vsoft");
driver.findElement(By.id("address1")).sendKeys("Test 81/1,2nd cross");
driver.findElement(By.id("city")).sendKeys("XYZ");
// Select State
WebElement statedropdown=driver.findElement(By.name("id_state"));
Select oSelect=new Select(statedropdown);
oSelect.selectByValue("4");
driver.findElement(By.name("postcode")).sendKeys("51838");
// Select Country
WebElement countrydropDown=driver.findElement(By.name("id_country"));
Select oSelectC=new Select(countrydropDown);
oSelectC.selectByVisibleText("United States");
//Enter Mobile Number
driver.findElement(By.id("phone_mobile")).sendKeys("234567890");
driver.findElement(By.xpath("//input[@name=\"alias\"]")).clear();
driver.findElement(By.xpath("//input[@name=\"alias\"]")).sendKeys("Office");
driver.findElement(By.name("submitAccount")).click();
StringuserText=driver.findElement(By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[1]/
a")).getText();
// Validate that user has created
if(userText.contains("Vsoft")) {
System.out.println("User Verified,Test case Passed");
}
else {
System.out.println("User Verification Failed,Test case Failed");
}
}
}

Negative Scenarios

2. Test Case - Verify invalid email address error.

Steps to Automate:

i. Open this URL http://automationpractice.com/index.php


ii. Click on the sign-in link.
iii. Enter an invalid email address in the email box and click enter.
lOMoAR cPSD| 7367891

iv. Validate that an error message is displaying saying "Invalid email address."

3. Test Case - Verify error messages for mandatory fields.

Steps to Automate:

i. Open this URL http://automationpractice.com/index.php


ii. Click on the sign-in link.
iii. Enter your email address and click the Register button.
iv. Leave the mandatory fields (marked with *) blank and click the Register button.
v. Verify that an error has been displayed for the mandatory fields.

4. Test Case - Verify error messages for entering incorrect values in fields.

Steps to Automate:

i. Open this URL http://automationpractice.com/index.php


ii. Click on the sign-in link.
iii. Enter your email address and click the Register button.
iv. Enter incorrect values in fields like., enter numbers in first and last name, city field, etc.,
and enter alphabets in Mobile no, Zip postal code, etc., and click on the 'Register' button.
v. Verify that error messages for respective fields are displaying.
vi. Try automating the above scenarios using Selenium commands, if you face any difficulty
please refer to the Selenium Tutorial series.

5. Automate the 'Search Product' feature of Amazon like e-commerce website with
Selenium

(1).Test Case - Automate the 'Search Product' feature of the e-commerce website with Selenium.

Steps to Automate:

i. Open link http://automationpractice.com/index.php


ii. Move your cursor over the Women's link.
iii. Click on the sub-menu 'T-shirts'
iv. Get the Name/Text of the first product displayed on the page.
v. Now enter the same product name in the search bar present at the top of the page and
click the search button.
vi. Validate that the same product is displayed on the searched page with the same details
which were displayed on T-Shirt's page.

Automation Code for Product Search:

The following code is contributed by Uday


lOMoAR cPSD| 7367891

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import io.github.bonigarcia.wdm.WebDriverManager;
public class EcomPractice2 {
public static void main(String[] args) throws InterruptedException{
WebDriverManager.chromedriver().setup();
WebDriver driver=new ChromeDriver();
String URL="http://automationpractice.com/index.php";

driver.get(URL);
driver.manage().window().maximize();
// Initialise Actions class object
Actions actions=new Actions(driver);
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
WebElement womenTab=driver.findElement(By.linkText("WOMEN"));
WebElement
TshirtTab=driver.findElement(By.xpath("//div[@id='block_top_menu']/ul/li[1]/ul/li[1]/ul//a[
@title='T-shirts']"));
actions.moveToElement(womenTab).moveToElement(TshirtTab).click().perform();
Thread.sleep(2000);
// Get Product Name
String
ProductName=driver.findElement(By.xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/div[3]/div
[2]/ul[1]/li[1]/div[1]/div[2]/h5[1]/a[1]")).getText();
System.out.println(ProductName);
driver.findElement(By.id("search_query_top")).sendKeys(ProductName);
driver.findElement(By.name("submit_search")).click();
// Get Name of Searched Product
String
SearchResultProductname=driver.findElement(By.xpath("/html[1]/body[1]/div[1]/div[2]/div[
1]/div[3]/div[2]/ul[1]/li[1]/div[1]/div[2]/h5[1]/a[1]")).getText();
// Verify that correct Product is displaying after search
if(ProductName.equalsIgnoreCase(SearchResultProductname)) {
System.out.println("Results Matched;Test Case Passed");
}else{
System.out.println("Results NotMatched;Test Case Failed");
}
// Close the browser
driver.close();
}
}

6. Automate the 'Buy Product' feature of Amazon like an e-commerce website with Selenium
The most important function of an e-commerce website is buying a product, which includes various
steps like selecting a product, selecting size/color, adding to the cart, checkout, etc. You will find
every test scenario along with the automation code in the following section.
lOMoAR cPSD| 7367891

(1) Test Case - Automate the end-to-end "Buy Product" feature of the e-commerce website.

Steps to Automate:

i. Open link http://automationpractice.com/index.php


ii. log in to the website.
iii. Move your cursor over the Women's link.
iv. Click on the sub-menu 'T-shirts'.
v. Mouse hover on the second product displayed.
vi. 'More' button will be displayed, click on the 'More' button.
vii. Increase quantity to 2.
viii. Select size 'L'
ix. Select color.
x. Click the 'Add to Cart' button.
xi. Click the 'Proceed to checkout' button.
xii. Complete the buy order process till payment.
xiii. Make sure that the Product is ordered.

The following code for Purchase Product is contributed by Uday:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import io.github.bonigarcia.wdm.WebDriverManager;
public class EcomExpert {
public static void main(String[] args){
WebDriverManager.chromedriver().setup();
WebDriver driver=new ChromeDriver();
String URL="http://automationpractice.com/index.php";
// Open URL and Maximize browser window
driver.get(URL);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS);
//Click on Sign in
driver.findElement(By.linkText("Sign in")).click();
//Login
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("passwd")).sendKeys("PKR@PKR");
driver.findElement(By.id("SubmitLogin")).click();
//Click on Women
driver.findElement(By.linkText("WOMEN")).click();
WebElement
SecondImg=driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div[2]/ul/li[2]
lOMoAR cPSD| 7367891

/div/div[1]/div/a[1]/img"));
WebElement
MoreBtn=driver.findElement(By.xpath("/html/body[1]/div[1]/div[2]/div[1]/div[3]/div[2]/ul/li
[2]/div[1]/div[2]/div[2]/a[2]"));
Actions actions=new Actions(driver);
actions.moveToElement(SecondImg).moveToElement(MoreBtn).click().perform();
//Change quantity by 2
driver.findElement(By.id("quantity_wanted")).clear();
driver.findElement(By.id("quantity_wanted")).sendKeys("2");
//Select size as L
WebElement Sizedrpdwn=driver.findElement(By.xpath("//*[@id='group_1']"));
Select oSelect=new Select(Sizedrpdwn);
oSelect.selectByVisibleText("M");
//Select Color
driver.findElement(By.id("color_11")).click();

//Click on add to cart


driver.findElement(By.xpath("//p[@id='add_to_cart']//span[.='Add to cart']")).click();
//Click on proceed
driver.findElement(By.xpath("/html//div[@id='layer_cart']//a[@title='Proceed to
checkout']/span")).click();
//Checkout page Proceed

driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/p[2]/a[1]/span")).click(
);
driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/form/p/button/span")).
click();
//Agree terms&Conditions
driver.findElement(By.xpath("//*[@id=\"cgv\"]")).click();
driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/div/form/p/button/span
")).click();
//Click on Payby Check
driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/div/div[3]/div[2]/div/p
/a")).click();
//Confirm the order
driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/form/p/button/span")).
click();
//Get Text
String
ConfirmationText=driver.findElement(By.xpath("//div[@id='center_column']/p[@class='aler
t alert-success']")).getText();
// Verify that Product is ordered
if(ConfirmationText.contains("complete")) {
System.out.println("Order Completed: Test Case Passed");
}
else {
System.out.println("Order Not Successfull: Test Case Failed");
}
}
}
(2) Test Case - Verify that 'Add to Wishlist' only works after login.
lOMoAR cPSD| 7367891

Steps to Automate:

i. Open link http://automationpractice.com/index.php


ii. Move your cursor over the Women's link.
iii. Click on the sub-menu 'T-shirts'.
iv. Mouse hover on the second product displayed.
v. 'Add to Wishlist' will appear on the bottom of that product, click on it.
vi. Verify that the error message is displayed 'You must be logged in to manage your wish
list.'

(3) Test Case - Verify that Total Price is reflecting correctly if the user changes quantity on the
'Shopping Cart Summary' Page.

Steps to Automate:

i. Open link http://automationpractice.com/index.php


ii. Log in to the website.
iii. Move your cursor over the Women's link.
iv. Click on the sub-menu 'T-shirts'.
v. Mouse hover on the second product displayed.
vi. 'More' button will be displayed, click on the 'More' button.
vii. Make sure the quantity is set to 1.
viii. Select size 'M'
ix. Select the color of your choice.
x. Click the 'Add to Cart' button.
xi. Click the 'Proceed to checkout' button.
xii. Change the quantity to 2.
xiii. Verify that the Total price is changing and reflecting the correct price.
xiv. Similar way you can add a few more test cases.
lOMoAR cPSD| 7367891

Result :
Thus the Automate the testing of e-commerce applications using Selenium was done and
these output was verified successfully.
lOMoAR cPSD| 7367891

Ex.no : 08
Date : Integrate TestNG with the above test automation.

Aim :
To Integrate TestNG with the above test automation.

Procedures :

TestNG Framework?
TestNG is an open-source test automation framework for Java. It is developed on the same
lines as JUnit and NUnit. A few advanced and useful features provided by TestNG make it a
more robust framework than its peers. The NG in TestNG stands for ‗Next Generation.‘

Installing and Setting up TestNG

Below are the steps to install TestNG:


1. Install Eclipse IDE from the Eclipse website. It serves as a platform for you to code on and
write your test cases
2. Once installed, go to help and navigate to the ‗Eclipse Marketplace‘. The referenced snapshot
is below:

3. Click on ‗Eclipse Marketplace‘. You will be directed to the marketplace modal. Type TestNG in
the search keyword and hit ‗Go‘. The referenced snapshot is below:
lOMoAR cPSD| 7367891

4. If TestNG is not installed in your Eclipse, rather than the ‗Installed‘ button you would see
‗install‘. Click on install and your TestNG framework will be installed in your Eclipse. As a
good practice, Eclipse would recommend you to restart to use the features of the installed plugin
5. Post-restarting your Eclipse, re-verify whether you can see options for creating a TestNG class
or not as below:

How to Write your First TestNG Test


Step #1 – Create your first TestNG class by right-clicking on the package and selecting the‘ Other‘
folder from the ‗New‘ option.

Step #2 – From the wizard modal, select the TestNG folder and select the TestNG class as below:
lOMoAR cPSD| 7367891

Step #3 – Click the ‗New‘ button and choose any predefined annotations you wish to have in your
class as below:

Step #4 – Click on finish, and you are ready to start writing your first TestNG class. Reference
screenshot below, containing the defined methods with the annotations chosen in the step above:

Step #5 – We will automate the sign-up flow using these annotations in the code snippet below.

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
public class FirstTestWithTestNGFramework {
lOMoAR cPSD| 7367891

WebDriver driver;
@BeforeClass
public void testSetup()
{
System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
@BeforeMethod
public void openBrowser()
{
driver.get("https://www.browserstack.com/");
driver.findElement(By.id("signupModalButton")).click();
System.out.println("We are currently on the following URL" +driver.getCurrentUrl());
}
@Test(description="This method validates the sign up functionality")
public void signUp()
{
driver.findElement(By.id("user_full_name")).sendKeys("user_name");
driver.findElement(By.id("user_email_login")).sendKeys("email_id");
driver.findElement(By.id("user_password")).sendKeys("password");
driver.findElement(By.xpath("//input[@name='terms_and_conditions']")).click();
driver.findElement(By.id("user_submit")).click();
}
@AfterMethod
public void postSignUp()
{
System.out.println(driver.getCurrentUrl());
}
lOMoAR cPSD| 7367891

@AfterClass
public void afterClass()
{
driver.quit();
}
}
Step #6 – To execute your report, you can either choose to run directly as a TestNG class or run
the XML file created which contains the class name and details. Below is the auto-created
TestNG XML file:

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


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name=".FirstTestWithTestNGFramework"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Step #7 – To access the TestNG report, you only need to refresh your project folder. A folder as
‗test output‘ will be auto-generated. Within this folder, you shall see a file ‗index.html‘ as below:
lOMoAR cPSD| 7367891

Step #8 – Double click on it and you can view your TestNG reports, showing the passed and failed
methods of the execution as below.

Step #9 – As a QA or tester, the next step is to validate your tests. If you did not validate your test
methods, it basically means your testing process is incomplete.
lOMoAR cPSD| 7367891

Result :
Thus the Integrate TestNG with the above test automation was done and these output was
verified successfully.
lOMoAR cPSD| 7367891

Ex.no : 09
Date : Build a data-driven framework using Selenium and TestNG

Aim :
To Build a data-driven framework using Selenium and TestNG.

Procedures :

Data Driven Testing Framework in Selenium?

Data Driven framework is used to drive test cases and suites from an external data feed. The
data feed can be data sheets like xls, xlsx, and csv files.

Data Driven Testing Example

 To download Apache POI Jar files click here. Download the zip file or tar file as per
requirement and place them along with the set of Selenium JARs and configure your build
path.
 Now let‘s understand how to write the first test case. An excel file to read the data from the
sheet. The user has entered different combinations of username and password in the sheet.
lOMoAR cPSD| 7367891

 Here, the target is to enter all these combinations of username and password into the Browser
stack Sign in page as shown below.

Let‘s write a code snippet to read the data files.


Step 1: Go to the Eclipse IDE and create a project. Add all the dependencies for TestNG, Selenium
and Apache POI.
Step 2: Create a class file to write the functionality
Code :
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ExcelExample{
@Test(dataProvider="testdata")
public void demoClass(String username, String password) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "Path of Chrome Driver");
Webdriver driver = new ChromeDriver();
driver.get("<a href="https://www.browserstack.com/users/sign_in</a>");
lOMoAR cPSD| 7367891

driver.findElement(By.name("user[login]")).sendKeys(username);
driver.findElement(By.name("user[password]")).sendKeys(password);
driver.findElement(By.name("commit")).click();
Thread.sleep(5000);
Assert.assertTrue(driver.getTitle().matches("BrowserStack Login | Sign Into The Best Mobile &
Browser Testing Tool"), "Invalid credentials");
System.out.println("Login successful");
}
@AfterMethod
void ProgramTermination() {
driver.quit();
}
@DataProvider(name="testdata")
public Object[][] testDataExample(){
ReadExcelFile configuration = new ReadExcelFile("Path_of_Your_Excel_File");
int rows = configuration.getRowCount(0);
Object[][]signin_credentials = new Object[rows][2];

for(int i=0;i<rows;i++)
{
signin_credentials[i][0] = config.getData(0, i, 0);
signin_credentials[i][1] = config.getData(0, i, 1);
}
return signin_credentials;
}
}

 In the above code, there is a ―TestDataExample() method‖ in which the user has created
an object instance of another class named ―ReadExcelFile‖. The user has mentioned the
path to the excel file. The user has further defined a for loop to retrieve the text from the
excel workbook. But to fetch the data from the excel file, one needs to write a class file
for the same.
lOMoAR cPSD| 7367891

Code :

import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile{
XSSFWorkbook work_book;
XSSFSheet sheet;
public ReadExcelFile(String excelfilePath) {
try {
File s = new File(excelfilePath);
FileInputStream stream = new FileInputStream(s);
work_book = new XSSFWorkbook(stream);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column){
sheet = work_book.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex){
int row = work_book.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}

 In the code above, the user has used Apache POI libraries to fetch the data from the excel
file. Next, it will point to the data present in the excel file and then enter the relevant
username and password to the sign in page.
lOMoAR cPSD| 7367891

Result :
Thus the mini project of Build a data-driven framework using Selenium and TestNG was
done and these output was verified successfully.
lOMoAR cPSD| 7367891

Ex.no : 10
Date : Build Page object Model using Selenium and TestNG

Aim :
To Build Page object Model using Selenium and TestNG.

Procedures :

After having introduced the Selenium + TestNG combination in my previous post, I would like to show you how
to apply the Page Object Model, an often used method for improving maintainability of Selenium tests, to this
setup. To do so, we need to accomplish the following steps:

 Create Page Objects representing pages of a web application that we want to test

 Create methods for these Page Objects that represent actions we want to perform within the pages that
they represent

 Create tests that perform these actions in the required order and performs checks that make up the test
scenario

 Run the tests as TestNG tests and inspect the results

Creating Page Objects for our test application

For this purpose, again I use the ParaBank demo application that can be found here. I‘ve narrowed the scope of
my tests down to just three of the pages in this application: the login page, the home page (where you end up after
a successful login) and an error page (where you land after a failed login attempt). As an example, this is the code
for the login page:

package com.ontestautomation.seleniumtestngpom.pages;

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

public class LoginPage {

private WebDriver driver;

public LoginPage(WebDriver driver) {

this.driver = driver;

if(!driver.getTitle().equals("ParaBank | Welcome | Online Banking")) {


driver.get("http://parabank.parasoft.com");
}
}

public ErrorPage incorrectLogin(String username, String password) {

driver.findElement(By.name("username")).sendKeys(username);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.xpath("//input[@value='Log In']")).click();
return new ErrorPage(driver);
}
lOMoAR cPSD| 7367891

public HomePage correctLogin(String username, String password) {

driver.findElement(By.name("username")).sendKeys(username);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.xpath("//input[@value='Log In']")).click();
return new HomePage(driver);
}
}

It contains a constructor that returns a new instance of the LoginPage object as well as two methods that we can
use in our tests: incorrectLogin, which sends us to the error page and correctLogin, which sends us to the home
page. Likewise, I‘ve constructed Page Objects for these two pages as well. A link to those implementations can
be found at the end of this post.

Note that this code snippet isn‘t optimized for maintainability – I used direct references to element properties
rather than some sort of element-level abstraction, such as an Object Repository.

Creating methods that perform actions on the Page Objects

You‘ve seen these for the login page in the code sample above. I‘ve included similar methods for the other two
pages. A good example can be seen in the implementation of the error page Page Object:

package com.ontestautomation.seleniumtestngpom.pages;

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

public class ErrorPage {

private WebDriver driver;

public ErrorPage(WebDriver driver) {

this.driver = driver;
}

public String getErrorText() {

return driver.findElement(By.className("error")).getText();
}
}

By implementing a getErrorText method to retrieve the error message that is displayed on the error page, we can
call this method in our actual test script. It is considered good practice to separate the implementation of your
Page Objects from the actual assertions that are performed in your test script (separation of responsibilities). If
you need to perform additional checks, just add a method that returns the actual value displayed on the screen to
the associated page object and add assertions to the scripts where this check needs to be performed.

Create tests that perform the required actions and execute the required checks

Now that we have created both the page objects and the methods that we want to use for the checks in our test
scripts, it‘s time to create these test scripts. This is again pretty straightforward, as this example shows (imports
removed for brevity):
package com.ontestautomation.seleniumtestngpom.tests;

public class TestNGPOM {

WebDriver driver;
lOMoAR cPSD| 7367891

@BeforeSuite
public void setUp() {

driver = new FirefoxDriver();


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@Parameters({"username","incorrectpassword"})
@Test(description="Performs an unsuccessful login and checks the resulting error message")
public void testLoginNOK(String username, String incorrectpassword) {

LoginPage lp = new LoginPage(driver);


ErrorPage ep = lp.incorrectLogin(username, incorrectpassword);
Assert.assertEquals(ep.getErrorText(), "The username and password could not be verified.");
}

@AfterSuite
public void tearDown() {

driver.quit();
}
}
Note the use of the page objects and the check being performed using methods in these page object
implementations – in this case the getErrorText method in the error page page object.

As we have designed our tests as Selenium + TestNG tests, we also need to define a testng.xml file that defines
which tests we need to run and what parameter values the parameterized testLoginOK test takes. Again, see my
previous post for more details.

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

<suite name="My first TestNG test suite" verbose="1" >


<parameter name="username" value="john"/>
<parameter name="password" value="demo"/>
<test name="Login tests">
<packages>
<package name="com.ontestautomation.seleniumtestngpom.tests" />
</packages>
</test>
</suite>

Run the tests as TestNG tests and inspect the results

Finally, we can run our tests again by right-clicking on the testng.xml file in the Package Explorer and selecting
‗Run As > TestNG Suite‘. After test execution has finished, the test results will appear in the ‗Results of running
suite‘ tab in Eclipse. Again, please note that using meaningful names for tests and test suites in the testng.xml file
make these results much easier to read and interpret.

Result :
Thus the mini project of Build Page object Model using Selenium and TestNG
wasdone and these output was verified successfully.
lOMoAR cPSD| 7367891

Ex.no : 10
Date : Build BDD framework with Selenium, TestNG and Cucumber

Aim :
To Build BDD framework with Selenium, TestNG and Cucumber
.

Procedures :

This new age requires all development to be test driven and Cucumber is a great tool to support
behavioral driven development. It also creates documentation automatically and easily shareable.
Cucumber bridges the gap between business and technical users. Users can write test cases in plain
English and the implementation can follow. It also serves the purpose of end-to-end testing framework.

TestNG is a testing framework like Junit. The advantages TestNG provides are:
1. It can run tests in parallel
2. Supports advance annotations like BeforeSuite/AfterSuite etc.
3. Grouping of tests are allowed
and so on.

So it makes sense to create a test suite which has a combination of both. My post here provides the details
of the test suite which combines both TestNG and cucumber and uses selenium webdriver to execute test
cases on a couple of websites. There are a bunch of features I implemented which can be utilized to create
enterprise grade test suite. In the end, I‘ll also highlight how to automate the test suite using Gitlab.

So let‘s jump in.


This app is a simple gradle app and gradle is configured to execute TestNG framework.
So first thing first are the dependencies —
dependencies {
implementation 'org.seleniumhq.selenium:selenium-java:4.1.3'
implementation 'io.github.bonigarcia:webdrivermanager:5.1.0'
implementation 'org.testng:testng:7.5'
implementation 'io.cucumber:cucumber-java:7.2.3'
implementation 'io.cucumber:cucumber-testng:7.2.3'
implementation 'org.slf4j:slf4j-simple:1.7.35'
}
Below is snippet of build.gradle that can be used to configure gradle to execute the TestNG suite —
test {
useTestNG() {
suites "testng.xml"
testLogging.showStandardStreams = true
//report generation delegated to TestNG library:
useDefaultListeners = true
outputDirectory = file("$project.buildDir//testngOutput")
}
//turn off Gradle's HTML report to avoid replacing the reports generated by TestNG library:
reports.html.enabled(false)

systemProperty 'platform', System.getProperty('platform')


}
While here on the build.gradle, I also configured the gradle cucumber reporting so as to generate
cucumber reports automatically —
plugins {
lOMoAR cPSD| 7367891

id 'java'
id "com.github.spacialcircumstances.gradle-cucumber-reporting" version "0.1.24"
}
cucumberReports {
outputDir = file('build/reports/')
buildId = '0'
reports = files('build/cucumber-reports/cucumber.json')
}
So pretty much when the suite is executed we‘ll see below outputs:
1. TestNG report under build/testngOutput
2. Cucumber reports under build/reports/
3. Screen shots of test cases under build/screenshots (To be covered later in the post)
Let‘s dive-in on the TestRunner. It is a JAVA class implementing the TestNG suite which is used to
execute cucumber features. Cucumber features are configured as —
@CucumberOptions(
features = {"src/test/resources/featureFiles"},
glue = {"com.company.step.definitions"},
monochrome = true,
dryRun = false,
plugin = {
"json:build/cucumber-reports/cucumber.json",
"rerun:build/cucumber-reports/rerun.txt"
})

glue option here tells which package has the implementation of features.

To execute the TestNG suite, I have implemented these functions —


@Test(groups = "cucumber", description = "Runs Cucumber Scenarios", dataProvider = "scenarios")
public void runScenario(PickleWrapper pickleWrapper, FeatureWrapper featureWrapper) {
testNGCucumberRunner.runScenario(pickleWrapper.getPickle());
}

@DataProvider
public Object[][] scenarios() {
return testNGCucumberRunner.provideScenarios();
}
DataProvider here provides all the scenarios and using TestNGCucumberRunner all those scenarios
are run.
This TestRunner class is configured to run using a testng.xml file (which was configured using gradle) —
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Test Suite">
<parameter name="platform" value="${platform}" />

<test name="TestSuite" >


<classes>
<class name="com.company.runner.TestRunner"/>
</classes>
</test>
</suite>
Let‘s jump to Selenium webdriver initialization. Here I have downloaded the chrome drivers and
hardcoded them in the project. Selenium also automatically downloads the webdriver based on the
browser installed (also configured in the code) and execute test cases.
In my case I have downloaded, but if you want selenium to use latest drivers, just delete the drivers and
configure code accordingly.
Selenium supports different browsers and also remote browsers. The project doesn‘t touch those points,
but a simple functionality can always be written to execute all test cases in all the browsers.
lOMoAR cPSD| 7367891

Let‘s initialize the webdriver —


public class TestRunner {
private TestNGCucumberRunner testNGCucumberRunner;
public static WebDriver webdriver;

@BeforeSuite(alwaysRun = true)
@Parameters({"platform"})
public void setUpCucumber(String platform) throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());

if (platform.equalsIgnoreCase("Windows")) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") +
"/src/main/resources/Drivers/chromedriver_windows_100.0.4896.60.exe");
ChromeOptions options = new ChromeOptions();
//options.setHeadless(true);
options.addArguments("--disable-notifications");
webdriver = new ChromeDriver(options);

} else if (platform.equalsIgnoreCase("Linux")) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") +
"/src/main/resources/Drivers/chromedriver_linux64_100.0.4896.60");
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
options.addArguments("--disable-notifications");
webdriver = new ChromeDriver(options);
}

log.info("Chrome Driver Initialized.");


}
A few things are happening here —
1. @BeforeSuite annotation is used. This will ensure that webdriver is initialized before the test
suite is started
2. Hardcoded drivers based on platform which is either Windows or Linux
3. @Parameters annotation is used. This ensures that any parameter that is passed to test suite is
automatically captured. In our case, we configured gradle to pass the parameter as property
parameter like this —
systemProperty 'platform', System.getProperty('platform')
You can check build.gradle section when we configured the test stage of gradle.
Similarly, I have also implemented the @AfterSuite annotation to close webdriver and quit TestNG —
@AfterSuite(alwaysRun = true)
public void tearDownClass() throws Exception {
webdriver.quit();
testNGCucumberRunner.finish();
}
So now our Runner is ready. Let‘s implement the test case cucumber scenarios. For scenarios, first thing
is feature files. I have two feature files for sample testing here:
 Tests the reset button functionality of guru99 website
Feature: Reset Functionality Scenarios

Scenario Outline: Reset Functionality


Given User navigates to "<website>"
When User enter the Username "<username>" and Password "<password>"
Then Reset the credential

Examples:
lOMoAR cPSD| 7367891

| website | username | password |


| https://www.demo.guru99.com/v4 | test1 | test1 |
| https://www.demo.guru99.com/v4 | test2 | test2 |
 Test to check the Home button functionality of javatpoint website
Feature: Home Button Functionality Scenarios

Scenario Outline: Home Button Functionality


Given User navigates to "<website>"
When User clicks on Home Button
Then Home website "<website2>" is reached

Examples:
| website | website2 |
| https://www.javatpoint.com/gui-testing | https://www.javatpoint.com/ |
| https://www.javatpoint.com/gui-testing | https://www.javatpoint.com/ |
Plain English and this is the advantage Cucumber provides. Business users and write test cases and
implementation can follow later
Before we jump into implementation, you need a @Before function to provide the scenario —
@Before
public void before(Scenario scenarioVal) {
this.scenario = scenarioVal;
log.info("Scenario: " + scenario.getName());
}

This needs to be there in all the test classes extending TestRunner.


Let‘s see the implementation now for test1 —
@Given("^User navigates to \"(.*)\"$")
public void user_navigates_to_website(String website) throws Exception {
log.info("User navigates to website: "+ website);
webdriver.get(website);
webdriver.manage().window().maximize();
Thread.sleep(2000);
}
@When("^User enter the Username \"(.*)\" and Password \"(.*)\"$")
public void enter_the_Username_and_Password(String username,String password) throws Throwable
{
webdriver.findElement(By.xpath("//input[@name='uid']")).sendKeys(username);
webdriver.findElement(By.xpath("//input[@name='password']")).sendKeys(password);
}
@Then("^Reset the credential$")
public void reset_the_credential() throws InterruptedException {
webdriver.findElement(By.xpath("//input[@name='btnReset']")).click();
}
Here we load the website into webdriver and then use XPATH to locate the website components. I am
using relative path and found the most easiest way to do this.
I installed a cromeplugin from — https://selectorshub.com/
Once you have it, its easy to locate xpath by right clicking on the component and copy relative path. The
advantage relative xpath provides is if there are any changes on the website, it has a high chances of being
immune to those changes.
Please note the way data is propagated from feature file to implementation.
For test2, here is the implementation —
@When("^User clicks on Home Button$")
public void user_clicks_on_home_button() throws Throwable
{
webdriver.findElement(By.xpath("//a[normalize-space()='Home']")).click();
}
lOMoAR cPSD| 7367891

@Then("^Home website \"(.*)\" is reached$")


public void home_website_is_reached(String expectedUrl) throws InterruptedException {
String url = webdriver.getCurrentUrl();
Assert.assertEquals(expectedUrl, url);
}
I am also asserting the value of URL here, test case will fail if the values won‘t match.
You can also get the screenshots of each test case using below code —
@After
public void screenCapture(Scenario scenario) throws Exception {
String filename = System.getProperty("user.dir") + "/build/screenshots/"
+ scenario.getName().replace(" ", "_") + "_" + scenario.getLine() + ".png";
log.info("Taking Screenshot --> " + filename );
byte screenshot[] = ((TakesScreenshot) webdriver).getScreenshotAs(OutputType.BYTES);
File f = new File(filename);
f.getParentFile().mkdirs();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(filename);
fos.write(screenshot);
}
This will ensure that screenshots are available at the end of each scenario and can be verified later.
Let‘s talk about execution now. Execution is simple, just issue below gradle command —
gradle test -Dplatform="Windows"
Let‘s talk about outputs and reporting.
 TestNG reports looks like this
lOMoAR cPSD| 7367891

 Cucumber reports looks like this

 And screenshots also got captured

Result :
Thus the mini project of Build BDD framework with Selenium, TestNG and Cucumber
was done and these output was verified successfully.

You might also like