CCS366-Software Testing and Automation-Lab-Manual
CCS366-Software Testing and Automation-Lab-Manual
CCS366-Software Testing and Automation-Lab-Manual
Name :………………………..
Year/Semester :………………………..
Degree/Dept. :………………………..
lOMoAR cPSD| 7367891
INDEX
lOMoAR cPSD| 7367891
4. Develop the test plan and design the test cases for an
inventory control system
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
DEPARTMENT MISSION
PROGRAM OUTCOMES
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.
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
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
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.
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
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
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
Checkout Page
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.
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.
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.
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.
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.
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.
Manual testing is a fundamental testing approach where human testers execute test cases without
lOMoAR cPSD| 7367891
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.
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.
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.
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.
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.
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.
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
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
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.
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
Steps to Automate:
iv. Validate that an error message is displaying saying "Invalid email address."
Steps to Automate:
4. Test Case - Verify error messages for entering incorrect values in fields.
Steps to Automate:
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:
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:
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();
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:
(3) Test Case - Verify that Total Price is reflecting correctly if the user changes quantity on the
'Shopping Cart Summary' Page.
Steps to Automate:
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.‘
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:
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:
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 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.
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.
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
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;
this.driver = driver;
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
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.
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;
this.driver = driver;
}
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;
WebDriver driver;
lOMoAR cPSD| 7367891
@BeforeSuite
public void setUp() {
@Parameters({"username","incorrectpassword"})
@Test(description="Performs an unsuccessful login and checks the resulting error message")
public void testLoginNOK(String username, String incorrectpassword) {
@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.
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.
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.
@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}" />
@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);
}
Examples:
lOMoAR cPSD| 7367891
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());
}
Result :
Thus the mini project of Build BDD framework with Selenium, TestNG and Cucumber
was done and these output was verified successfully.