STA - Lab Manual
STA - Lab Manual
LABORATORY RECORD
Name :
Reg.No. :
Subject :
Year/Semester :
ROEVER ENGINEERING COLLEGE
(Approved by AICTE, New Delhi and Affiliated to Anna University, Chennai)
(Inclusion under section 2 (f) and 12 (B) of the UGC act)
BONAFIDE CERTIFICATE
Held on………….……
Vision
Envisioned to become a leader in providing quality technical education, while shaping
socially responsible engineers.
Mission
1. To enhance academic quality through curriculum modernization, innovative teaching
methods, quality infrastructure and a strong focus on faculty competence.
3. To cultivate leadership skills that enable students to meet societal needs through ethical
practices, entrepreneurship, and community engagement.
Vision
To be a leader in Computer Science and Engineering Education, fostering graduates
who excel in technical education meet the evolving needs of industry and society.
Mission
1. Provide a rigorous learning environment in Computer Science and Engineering, enriched
with ample opportunities for hands-on practice, research and innovation.
2. Equip students with recent trends in computer science engineering through industry-
institute interactions with developing problem solving and analytical skills with sound
knowledge.
3. Imbibe ethical and human values, nurture interpersonal and entrepreneurial skills.
ROEVER ENGINEERING COLLEGE
(Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai)
(Inclusion under Section 2(f) and 12(B) of the UGC act, 1956)
ELAMBALUR (PO), PERAMBALUR – 621220.
PSO2: Analyze, design, synthesize and provide software solutions using latest software tools
and in domains like Machine Learning, Artificial Intelligence, Internet of things, Cloud
Computing, Data Sciences etc.
PEO1: Have successful career or higher studies and exhibit technical competence by providing
innovative software and hardware solutions.
PEO3: Contribute towards entrepreneurship and research, and exercise leadership through
effective communication, teamwork and knowledge upgradation through lifelong learning.
CO – PO / PSO MAPPING
Course Objectives:
Objectives of this course is to
S.No COURSE OBJECTIVES
5 To get an insight about test automation and the tools used for test automation
Course Outcomes:
At the end of this course students should be able to
CO. Highest
Course Outcome BTL
No
1 Understand the basic concepts of software testing and the need for software 3
testing
3 Design effective test cases that can uncover critical defects in the application 4
CO – PO – PSO MAP
COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
1 3 3 2 1 2 - - - 1 1 3 2 1 2 3
2 2 3 1 1 1 - - - 2 2 1 2 3 2 3
3 2 2 1 3 1 - - - 1 3 1 2 1 3 2
4 2 1 3 2 1 - - - 1 1 1 2 2 1 2
5 2 2 1 3 1 - - - 1 3 2 1 2 1 3
CCS366 2.2 2.2 1.6 2 1.2 - - - 1.2 2 1.6 1.8 2.2 1.8 2.6
CONTENTS
EX. Page.
Date NAME OF THE EXPERIMENT Marks Sign
NO. No.
Develop the test plan for testing an e-commerce web/mobile
1.
application (www.amazon.in).
2. Design the test cases for testing the e-commerce application
3.
4. Develop the test plan and design the test cases for an inventory
control system.
Execute the test cases against a client server or desktop
5.
application and identify the defects.
Test the performance of the e-commerce application
6.
Automate the testing of e-commerce applications using
7.
Selenium.
Integrate TestNG with the above test automation.
8.
AIM
To Develop the test plan for testing an e-commerce web/mobile application (www.amazon.com)
PROCEDURE
1. Test Objectives:
Verify that users can browse and search for products.
Confirm that products are displayed accurately with correct details.
Test the user registration and login process.
Validate the shopping cart and checkout process.
Test payment processing and order placement.
Check for responsiveness and usability on mobile devices.
Verify security aspects such as data encryption and session management.
2. Test Environment:
Web Browsers: Chrome, Firefox, Safari, Edge.
Mobile Devices: iOS and Android devices.
Testing Framework: Selenium WebDriver with Java.
Load Testing: Apache JMeter for performance testing.
Security Testing: OWASP ZAP or similar tool.
3. Test Cases:
Test cases should cover registration, login, product browsing, cart management,
payment processing, etc.
Include positive and negative scenarios, edge cases, and stress tests.
4. Test Execution:
Automate test cases using Selenium WebDriver.
Execute tests across different browsers and mobile devices.
Use load testing tools to simulate high user traffic and monitor performance.
Perform security testing to identify vulnerabilities.
5. Test Data:
Use real and dummy data for testing.
Test accounts, products, payment methods, addresses, etc.
6. Risks and Assumptions:
Risk: Changes in the website's structure might break automation scripts.
Risk: Mobile app updates might affect test scripts and compatibility.
1
Assumption: Test data in the environment matches real-world scenarios.
2
7. Deliverables:
Test reports summarizing test results, defects found, and performance analysis.
Documentation of test cases, procedures, and configurations.
Recommendations for improvements and fixes.
PROGRAM
Test Plan: User Registration
Test Cases:
TC-UR-01: Verify successful registration with valid information.
TC-UR-02: Verify registration failure with invalid email format.
TC-UR-03: Verify registration failure with existing email.
TC-UR-04: Verify appropriate error messages for failed registration attempts.
Selenium WebDriver Test Case Code: User Registration
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver; public
class AmazonUserRegistrationTest {
3
// Step 4: Fill in registration details
WebElement nameInput = driver.findElement(By.id("ap_customer_name"));
4
nameInput.sendKeys("John Doe");
WebElement emailInput =
driver.findElement(By.id("ap_email"));
emailInput.sendKeys("[email protected]");
WebElement passwordInput =
driver.findElement(By.id("ap_password"));
passwordInput.sendKeys("password123");
WebElement confirmPasswordInput =
driver.findElement(By.id("ap_password_check"));
confirmPasswordInput.sendKeys("password123");
// Close the
browser
driver.quit();
}
}
OUTPUT
User registration successful
5
TC-UL-02: Verify login failure with incorrect password.
TC-UL-03: Verify login failure with non-existent username.
TC-UL-04: Verify appropriate error messages for failed login attempts.
Selenium WebDriver Test Case Code: User Login
6
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver;
public class AmazonUserLoginTest {
WebElement passwordInput =
driver.findElement(By.id("ap_password"));
passwordInput.sendKeys("password123");
8
}
}
OUTPUT
User Login Successful
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver; public
class AmazonProductBrowsingTest {
10
WebElement firstProductPrice = driver.findElement(By.cssSelector(".product-item:first-child
.product-price"));
// Close the
browser
driver.quit();
}
}
OUTPUT
Product listing page accessed successfully
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
11
"path/to/chromedriver"); WebDriver driver = new ChromeDriver();
// Step 1: Navigate to Amazon product listing page
12
driver.get("https://www.amazon.com/products");
// Step 2: Select a product from the list
WebElement product = driver.findElement(By.cssSelector(".product-item:first-
child")); product.click();
// Step 3: Verify product details
WebElement productName = driver.findElement(By.cssSelector(".product-name"));
WebElement productPrice = driver.findElement(By.cssSelector(".product-price"));
WebElement productDescription = driver.findElement(By.cssSelector(".product-
description"));
// Step 4: Verify product images and thumbnails
WebElement productImage = driver.findElement(By.cssSelector(".product-
image")); productImage.click(); // Clicking on the image to view full size
// Step 5: Verify navigation back to product listing
driver.navigate().back();
// Close the
browser
driver.quit();
}
}
OUTPUT
Navigated to Amazon product listing
page Product selected from the list
Product details verified
Product images and thumbnails
verified Navigated back to product
listing TEST PLAN: Shopping Cart
TEST CASE:
TC-SC-01: Verify addition of products to the shopping cart.
TC-SC-02: Verify accurate display of product details and quantities in the cart.
TC-SC-03: Verify user can update quantities of products in the cart.
TC-SC-04: Verify user can remove products from the cart.
Selenium WebDriver Test Case Code: Shopping Cart
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
13
public class AmazonShoppingCartTest {
14
public static void main(String[] args) {
// Set up the WebDriver
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver"); WebDriver driver = new ChromeDriver();
// Step 1: Navigate to Amazon product listing page
driver.get("https://www.amazon.com/products");
// Step 4: Verify accurate display of product details and quantities in the cart
WebElement productNameInCart = driver.findElement(By.cssSelector(".cart-item:first-child
.product-name"));
WebElement productQuantityInCart = driver.findElement(By.cssSelector(".cart-item:first-child
.product-quantity"));
// Verification based on success or failure is not included due to the complexity of the shopping cart
page.
// Close the browser
driver.quit();
15
}
}
Output
Product added to cart successfully
Product details and quantities in cart verified
Product quantity updated successfully
Product removed from cart successfully
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
16
cvvInput.sendKeys("123");
17
// Step 3: Click on "Submit Payment"
WebElement submitButton = driver.findElement(By.id("submit-payment"));
submitButton.click();
// Close the
browser
driver.quit();
}
}
OUTPUT
// Depending on the specific scenario:
Payment submitted successfully and user receives confirmation
OR
Payment submission failed due to invalid payment information
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
18
// Step 1: Log in to Amazon account (assuming already logged in)
19
// Step 2: Navigate to order history page
driver.get("https://www.amazon.com/order-
history");
RESULT:
Thus, the test plan for testing an e-commerce web/mobile application was developed and
20
executed successfully.
21
EX.NO: 2 DESIGN THE TEST CASE FOR TESTING
THE DATE: E-COMMERCE APPLICATION
AIM
To Develop the test case for testing an e-commerce application.
PROCEDURE
1. Test Objectives:
Verify that users can browse and search for products.
Confirm that products are displayed accurately with correct details.
Test the user registration and login process.
Validate the shopping cart and checkout process.
Test payment processing and order placement.
Check for responsiveness and usability on mobile devices.
Verify security aspects such as data encryption and session management.
2. Test Environment:
Web Browsers: Chrome, Firefox, Safari, Edge.
Mobile Devices: iOS and Android devices.
Testing Framework: Selenium WebDriver with Java.
Load Testing: Apache JMeter for performance testing.
Security Testing: OWASP ZAP or similar tool.
3. Test Cases:
Test cases should cover registration, login, product browsing, cart management,
payment processing, etc.
Include positive and negative scenarios, edge cases, and stress tests.
4. Test Execution:
Automate test cases using Selenium WebDriver.
Execute tests across different browsers and mobile devices.
Use load testing tools to simulate high user traffic and monitor performance.
Perform security testing to identify vulnerabilities.
5. Test Data:
Use real and dummy data for testing.
Test accounts, products, payment methods, addresses, etc.
6. Risks and Assumptions:
Risk: Changes in the website's structure might break automation scripts.
Risk: Mobile app updates might affect test scripts and compatibility.
Assumption: Test data in the environment matches real-world scenarios.
22
7. Deliverables:
Test reports summarizing test results, defects found, and performance analysis.
Documentation of test cases, procedures, and configurations.
Recommendations for improvements and fixes.
PROGRAM
Test Plan: User Registration
Test Cases:
TC-UR-01: Verify successful registration with valid information.
TC-UR-02: Verify registration failure with invalid email format.
TC-UR-03: Verify registration failure with existing email.
TC-UR-04: Verify appropriate error messages for failed registration attempts.
Selenium WebDriver Test Case Code: User Registration
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver; public
class AmazonUserRegistrationTest {
23
// Step 4: Fill in registration details
WebElement nameInput = driver.findElement(By.id("ap_customer_name"));
24
nameInput.sendKeys("John Doe");
WebElement emailInput =
driver.findElement(By.id("ap_email"));
emailInput.sendKeys("[email protected]");
WebElement passwordInput =
driver.findElement(By.id("ap_password"));
passwordInput.sendKeys("password123");
WebElement confirmPasswordInput =
driver.findElement(By.id("ap_password_check"));
confirmPasswordInput.sendKeys("password123");
// Close the
browser
driver.quit();
}
}
OUTPUT
User registration successful
25
TC-UL-02: Verify login failure with incorrect password.
TC-UL-03: Verify login failure with non-existent username.
TC-UL-04: Verify appropriate error messages for failed login attempts.
Selenium WebDriver Test Case Code: User Registration
26
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
WebElement passwordInput =
driver.findElement(By.id("ap_password"));
passwordInput.sendKeys("password123");
28
driver.quit();
}
}
OUTPUT
User Login Successful
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver;
public class AmazonProductDetailsTest {
public static void main(String[] args) {
// Set up the WebDriver
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver"); WebDriver driver = new ChromeDriver();
// Step 1: Navigate to Amazon product listing page
driver.get("https://www.amazon.com/products");
// Step 2: Select a product from the list
WebElement product = driver.findElement(By.cssSelector(".product-item:first-
child")); product.click();
// Step 3: Verify product details
WebElement productName = driver.findElement(By.cssSelector(".product-name"));
WebElement productPrice = driver.findElement(By.cssSelector(".product-price"));
WebElement productDescription = driver.findElement(By.cssSelector(".product-
description"));
// Step 4: Verify product images and thumbnails
29
WebElement productImage = driver.findElement(By.cssSelector(".product-
image")); productImage.click(); // Clicking on the image to view full size
// Step 5: Verify navigation back to product listing
30
driver.navigate().back();
// Close the
browser
driver.quit();
}
}
Output
Navigated to Amazon product listing
page Product selected from the list
Product details verified
Product images and thumbnails verified
Navigated back to product listing
RESULT:
Thus, the test cases for testing an e-commerce application were developed and executed
successfully.
31
EX.NO: 3 TEST THE E-COMMERCE APPLICATION AND
REPORT DATE: THE DEFECTS IN IT
AIM:
To test the e-commerce application and report the defects in it.
PROCEDURE:
Defect 1: Incorrect Product Search
Defect Aim: Verify that the product search functionality returns correct results.
Correct Test Procedure:
Navigate to the e-commerce website's homepage.
Enter "Laptop" in the search bar.
Click the search button.
Verify that the search results list includes relevant products.
DEFECT OUTPUT
Defect: Search results not displayed.
RESULT:
Thus, In the above Program The defected in the e-commerce website is tested and rectified
successfully
33
EX.NO :4 DEVELOP THE TEST PLAN AND DESIGN THE TEST
CASES DATE: FOR AN INVENTORY CONTROL SYSTEM
AIM:
To develop the test plan and design the test cases for an inventory control system
PROCEDURE
Test Plan Scenarios:
Scenario 1: Add New Item
Launch the Chrome browser.
Navigate to the inventory control system's homepage.
Log in as an administrator.
Click on the "Add New Item" button.
Fill in the item details and submit the form.
Verify that the new item is listed in the inventory.
Expected Result: The new item should be added to the inventory and listed correctly.
Scenario 2: Update Item Details
Launch the Chrome browser.
Navigate to the inventory control system's homepage.
Log in as an administrator.
Search for an existing item by name or ID.
Click on the item to edit its details.
Update the item's details and save the changes.
Verify that the updated details are correctly reflected in the inventory.
Expected Result: The item's details should be updated as per the changes made and displayed accurately
in the inventory.
Scenario 3: Delete Item
Launch the Chrome browser.
Navigate to the inventory control system's homepage.
Log in as an administrator.
Search for an existing item by name or ID.
Select the item and click the "Delete" button.
Confirm the deletion.
Verify that the item is removed from the inventory.
Expected Result: The item should be successfully deleted from the inventory and no longer listed.
34
Scenario 4: Defect - Incorrect Item Quantity Calculation
Launch the Chrome browser.
Navigate to the inventory control system's homepage.
Log in as an administrator.
Search for an existing item by name or ID.
Observe the current quantity of the item.
Perform transactions (additions/subtractions) to change the quantity.
Verify that the calculated quantity matches the actual quantity.
Expected Result: A defect should be identified if the calculated quantity does not match the actual
quantity due to incorrect quantity calculation logic.
Defect Report: Defect Aim: Verify the accuracy of item quantity calculation. Procedure:
Navigate to the inventory control system's homepage.
Log in as an administrator.
Search for an existing item by name or ID.
Observe the current quantity of the item.
Perform transactions (additions/subtractions) to change the quantity.
Verify that the calculated quantity does not match the actual quantity. Output:
Calculated quantity is incorrect. Severity: Major Priority: High
Test Case Design: Add New Item
Test Case Name: Add New Item
Description: Verify that a new item can be successfully added to the inventory.
Preconditions: Logged in as an administrator.
Test Steps:
Click on the "Add New Item" button.
Fill in the item details: name, ID, category, quantity, etc.
Click the "Submit" button.
Expected Result: The new item should be added to the inventory and listed correctly.
PROGRAM :
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
driver.quit();
}
}
OUTPUT
No errors encountered. New item "New Product" added to the inventory.
RESULT:
Thus, the test plan and the test case for an inventory control system was developed and executed
successfully.
36
EX.NO: 5 EXECUTE THE TEST CASES AGAINST A CLIENT SERVER
OR DATE: DESKTOP APPLICATION AND IDENTIFY THE DEFECTS
AIM
To Execute the test cases against a client server or desktop application and identify the defects
PROCEDURE:
Test Environment:
Appium
Android Emulator or iOS Simulator
Mobile Application: YourMobileApp.apk (Android) or YourMobileApp.ipa (iOS)
Test Scenarios:
37
Scenario 4: Defect - Slow Response
Launch the Appium server.
Set desired capabilities to connect to the mobile device/emulator.
Automate the login process with valid credentials.
Introduce a delay in the application's response.
Verify that the user is not logged in within a reasonable time.
Expected Result: A defect should be identified if the login process takes an unreasonably long time to
complete.
Defect Report: Defect Aim: Verify the responsiveness of the login process. Procedure:
Launch the Appium server.
Set desired capabilities to connect to the mobile device/emulator.
Automate the login process with valid credentials.
Introduce a delay in the application's response.
Verify that the user is not logged in within a reasonable time. Output: Login process takes
longer than expected. Severity: Major Priority: High
Test Case Design: Successful Login
Test Case Name: Successful Login
Description: Verify that a user can successfully log in with valid credentials.
Preconditions: Appium server is running; Mobile app installed on emulator/simulator.
Test Steps:
Set desired capabilities for the mobile device/emulator.
Automate the login process with valid credentials.
Expected Result: The user should be logged in, and the welcome message with the
username should be displayed.
try {
driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), caps);
// Enter credentials
usernameField.sendKeys("testuser");
passwordField.sendKeys("testpass");
// Click login button
loginButton.click();
// Verify successful login
MobileElement welcomeMessage = driver.findElement(MobileBy.id("welcomeMessage"));
if (welcomeMessage.getText().equals("Welcome, testuser!")) {
System.out.println("Login successful.");
} else {
System.out.println("Defect: Login failed.");
}
driver.quit();
} catch (Exception e) {
System.out.println("Error: " +
e.getMessage());
}
}
}
OUTPUT(EXPECTED)
Login successful.
OUTPUT(DEFECT)
Defect: Login failed.
RESULT:
Thus, the test cases against a client server or desktop application and identification of defects
were done successfully.
39
EX NO: 6 TEST THE PERFORMANCE OF THE E-COMMERCE
APPLICATION DATE:
AIM:
To test the performance of the e-commerce application
PROCEDURE
Test Environment:
Web browser: Chrome
Selenium WebDriver with Java
E-commerce website URL: https://www.example-ecommerce.com
Page to Test: ProductCatalogPage
Test Scenarios:
Scenario 1: Measure Page Load Time
Launch the Chrome browser.
Navigate to the ProductCatalogPage.
Measure the time it takes for the page to fully load.
Expected Result: The page load time should be measured accurately and within an acceptable range.
Test Case Design: Measure Page Load Time
Test Case Name: Measure Page Load Time
Test Case ID: TC-PERF-001
Description: Measure the page load time of a specific page on the e-commerce application.
Preconditions: None
Test Steps:
Launch the Chrome browser.
Navigate to the ProductCatalogPage.
Measure the time it takes for the page to fully load.
Expected Result: The page load time should be measured accurately and within an
acceptable range.
CODE:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
40
WebDriver driver = new ChromeDriver();
long startTime, endTime, pageLoadTime;
// Wait for an element on the page to indicate page load completion (e.g., a product
list) driver.findElement(By.className("product-list"));
endTime =
System.currentTimeMillis();
pageLoadTime = endTime - startTime;
driver.quit();
}
}
OUTPUT:
Page Load Time: <Some Value> milliseconds
41
RESULT:
Thus, the performance of the e-commerce application was executed successfully.
42
EX NO: 7 AUTOMATE THE TESTING OF E-
COMMERCE DATE: APPLICATION USING SELENIUM
AIM
To automate the testing of an e-commerce application using selenium.
PROCEDURE
Login Module:
o Verify that a user can log in with valid credentials.
o Verify that an error is displayed when logging in with invalid credentials.
o Verify the "Forgot Password" functionality.
Product Browsing:
o Verify that products are displayed on the homepage.
o Verify that a user can search for products.
o Verify that a user can filter products based on different criteria.
Shopping Cart:
o Verify that a user can add products to the shopping cart.
o Verify that the shopping cart displays the correct items and quantities.
o Verify that a user can update the quantity of items in the cart.
Checkout Process:
o Verify that a user can proceed to checkout.
o Verify that the correct shipping information is displayed.
o Verify that the order total is calculated correctly.
43
o Test Case 10: Verify the ability to proceed to checkout.
o Test Case 11: Verify the display of correct shipping information.
o Test Case 12: Verify the correctness of the order total.
CODE
CODE FOR LOGIN MODULE
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver; public
class ECommerceTest {
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
45
System.out.println("Test Case 3 Failed: Login Successful");
}
usernameInput.sendKeys("valid_username")
;
passwordInput.sendKeys("valid_password");
loginButton.click();
// Close the
browser
driver.quit();
}
}
org.openqa.selenium.chrome.ChromeDriver; public
class ProductBrowsingTest {
47
WebElement searchInput =
driver.findElement(By.id("searchInput"));
searchInput.sendKeys("product_name");
searchInput.sendKeys(Keys.RETURN);
// Wait for search results to load (you might want to use WebDriverWait in a real-world scenario)
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
WebElement searchResults = driver.findElement(By.id("searchResults"));
if (searchResults.isDisplayed() && searchResults.getText().contains("product_name"))
{ System.out.println("Test Case 5 Passed: Search results are displayed for the product.");
} else {
System.out.println("Test Case 5 Failed: Search results are not displayed for the product.");
}
// Close the
browser
driver.quit();
}
}
CODE FOR SHOPPING CART
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
49
// Add more products to the cart if needed...
// Test Case 8: Verify the correctness of the items and quantities in the shopping cart.
WebElement cartIcon = driver.findElement(By.id("cartIcon"));
cartIcon.click();
WebElement cartItems = driver.findElement(By.id("cartItems"));
if (cartItems.isDisplayed() && cartItems.getText().contains("Product 1"))
{ System.out.println("Test Case 8 Passed: Product 1 is in the shopping cart.");
} else {
System.out.println("Test Case 8 Failed: Product 1 is not in the shopping cart.");
}
// Test Case 9: Verify the ability to update the quantity of items in the
cart. WebElement quantityInput =
driver.findElement(By.id("quantityInput")); quantityInput.clear();
quantityInput.sendKeys("2");
WebElement updateButton =
driver.findElement(By.id("updateButton")); updateButton.click();
// Wait for the cart to update (you might want to use WebDriverWait in a real-world scenario)
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Check if the quantity is updated
WebElement updatedQuantity =
driver.findElement(By.id("updatedQuantity")); if
(updatedQuantity.getText().equals("2")) {
System.out.println("Test Case 9 Passed: Quantity of Product 1 is updated to 2.");
} else {
System.out.println("Test Case 9 Failed: Quantity of Product 1 is not updated to 2.");
}
// Add more test cases and actions here...
// Close the
browser
driver.quit();
}
}
CODE FOR CHECKOUT PROCESS
50
import org.openqa.selenium.By;
51
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
53
OUTPUT:
Test Case 1 Passed: Valid Username
Test Case 2 Passed: Valid Password
Test Case 3 Passed: User Login successful
Test Case 4 Passed: Products are displayed on the homepage.
Test Case 5 Passed: Search results are displayed for the product
Test Case 9 Passed: Quantity of Product 1 is updated to 2.
Test Case 11 Passed: Shipping information is displayed correctly.
Test Case 12 Passed: Order total is correct.
RESULT
Thus, the automation of an e-commerce application using selenium has been executed
successfully.
54
EX NO: 8 INTEGRATE TESTNG WITH ABOVE TEST
AUTOMATION DATE:
AIM:
To integrate TestNG for testing an e-commerce application with test automation
PROCEDURE:
Login Module:
o Test Case 1: Verify successful login with valid credentials.
o Test Case 2: Verify error message for login with invalid credentials.
o Test Case 3: Verify the functionality of the "Forgot Password" link.
Product Browsing:
o Test Case 4: Verify that products are displayed on the homepage.
o Test Case 5: Verify the search functionality.
o Test Case 6: Verify product filtering options.
Shopping Cart:
o Test Case 7: Verify the addition of products to the shopping cart.
o Test Case 8: Verify the correctness of the items and quantities in the shopping cart.
o Test Case 9: Verify the ability to update the quantity of items in the cart.
Checkout Process:
o Test Case 10: Verify the ability to proceed to checkout.
o Test Case 11: Verify the display of correct shipping information.
o Test Case 12: Verify the correctness of the order total.
CODE
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
55
// Run test cases
runLoginModuleTests(driver);
56
runProductBrowsingTests(driver);
runShoppingCartTests(driver);
runCheckoutProcessTests(driver);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
57
e.printStackTrace();
}
58
WebElement searchResults = driver.findElement(By.id("searchResults"));
if (searchResults.isDisplayed() && searchResults.getText().contains("product_name"))
{ System.out.println("Test Case 5 Passed: Search results are displayed for the product.");
} else {
System.out.println("Test Case 5 Failed: Search results are not displayed for the product.");
}
}
// Test Case 9: Verify the ability to update the quantity of items in the
cart. WebElement quantityInput =
driver.findElement(By.id("quantityInput")); quantityInput.clear();
quantityInput.sendKeys("2");
WebElement updateButton =
driver.findElement(By.id("updateButton")); updateButton.click();
// Wait for the cart to update (you might want to use WebDriverWait in a real-world scenario)
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Check if the quantity is updated
WebElement updatedQuantity = driver.findElement(By.id("updatedQuantity"));
59
if (updatedQuantity.getText().equals("2")) {
System.out.println("Test Case 9 Passed: Quantity of Product 1 is updated to 2.");
} else {
System.out.println("Test Case 9 Failed: Quantity of Product 1 is not updated to 2.");
}
}
RESULT:
Thus, the automation of TestNG for testing an e-commerce application using selenium was
executed successfully.
61
EX NO:9. a BUILD A DATA-DRIVEN FRAMEWORK
USING DATE: SELENIUM AND TESTNG
AIM
To Build a data-driven framework using selenium and TestNG.
PROCEDURE
Create a CSV file (testdata.csv):
Create a CSV file with columns "Username" and "Password" containing test data.
Create a TestNG Test Class (LoginTest.java):
Use TestNG annotations to define the test methods.
Use @DataProvider to read test data from the CSV file.
Configure TestNG XML File (testng.xml):
Create a TestNG XML file to configure the execution of your test class.
Run the Test:
Execute the TestNG XML file to run your data-driven test.
Test Cases:
Login with valid credentials:
Login with invalid credentials:
CODE
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import
org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import
java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
62
public class LoginTest
{ @Test(dataProvider =
"loginData")
public void testLoginWithValidCredentials(String username, String password) {
63
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
// Open the login page
driver.get("url_of_your_application_login_page");
// Locate username and password fields
WebElement usernameField = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("loginButton"));
// Enter valid username and password
usernameField.sendKeys(username);
passwordField.sendKeys(password);
// Click on the login button
loginButton.click();
// Verify successful login
WebElement welcomeMessage = driver.findElement(By.id("welcomeMessage"));
Assert.assertTrue(welcomeMessage.isDisplayed(), "Login failed for user: " + username);
// Close the
browser
driver.quit();
}
@Test(dataProvider = "loginData")
public void testLoginWithInvalidCredentials(String username, String password) {
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
// Open the login page
driver.get("url_of_your_application_login_page");
// Locate username and password fields
WebElement usernameField = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("loginButton"));
// Enter invalid username and password
usernameField.sendKeys(username);
passwordField.sendKeys(password);
64
Assert.assertTrue(errorMessage.isDisplayed(), "Error message not displayed for user: " +
username);
// Close the
browser
driver.quit();
}
@DataProvider(name =
"loginData") public Object[][]
readData() {
List<Object[]> testData = new ArrayList<>();
String csvFile = "path/to/testdata.csv";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile)))
{ String line;
while ((line = br.readLine()) != null)
{ String[] data = line.split(",");
testData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
}
Object[][] result = new Object[testData.size()][2];
for (int i = 0; i < testData.size(); i++) {
result[i] = testData.get(i);
}
return result;
}
}
Configure TestNG XML File (testng.xml):
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestSuite">
<test name="DataDrivenTest">
<classes>
<class name="LoginTest"/>
</classes>
</test>
</suite>
65
OUTPUT
Username : John
Password : 123
Login
Successful
RESULT:
Thus the data driven framework using selenium and TestNG was executed successfully.
66
EX NO:9. b BUILD PAGE OBJECT MODEL USING SELENIUM AND
TESTNG DATE:
AIM
To build a page object model using Selenium and TestNG.
PROCEDURE
Create Page Object Classes:
Create a class for each web page. Include web elements and methods representing the actions
on that page.
Create a Test Class using TestNG:
Use TestNG annotations to define the test methods.
Instantiate the Page Object classes and use them in your test methods.
Run the Test:
Execute the TestNG XML file or run the test class directly to run your tests.
CODE
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
68
passwordField.sendKeys(password);
}
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver"); driver = new ChromeDriver();
loginPage = new LoginPage(driver);
}
@Test
public void testLoginWithValidCredentials() {
loginPage.openLoginPage("url_of_your_application_login_page");
69
loginPage.enterUsername("valid_username");
loginPage.enterPassword("valid_password");
70
loginPage.clickLoginButton();
@Test
public void testLoginWithInvalidCredentials() {
loginPage.openLoginPage("url_of_your_application_login_page");
loginPage.enterUsername("invalid_username");
loginPage.enterPassword("invalid_password");
loginPage.clickLoginButton();
@AfterMethod
public void tearDown() {
driver.quit();
}
}
OUTPUT :
User Login Successful
RESULT
Thus, the page object model using selenium and TestNG has been built successfully.
71
EX NO:9.c BUILD A BDD FRAMEWORK USING
SELENIUM, DATE: TESTNG AND CUCUMBER
AIM
To build a BDD framework using selenium,testng and cucumber.
PROCEDURE:
1. Create a Maven Project:
Use your IDE (Eclipse, IntelliJ, etc.) to create a new Maven project.
2. Add Dependencies:
Add dependencies for Selenium, TestNG, and Cucumber in the `pom.xml` file.
3. Create Page Object Classes:
Create a `pages` package and implement the `LoginPage` class for the login page.
4. Create Feature Files:
Create a `resources` directory and a `features` sub-directory.
Write Gherkin-style scenarios in a `login.feature` file.
5. Create Step Definition Classes:
Create a `step_definitions` directory.
Implement the `StepDefinitions` class with step definition methods.
6. Set Up TestNG XML File:
Create a TestNG XML file (e.g., `testng.xml`) and configure the Cucumber runner class.
7. Write Selenium Code in Step Definitions:
Use Selenium code in the `StepDefinitions` class to interact with web elements.
Utilize methods from the `LoginPage` class.
8. Run the Tests:
Run the TestNG XML file to execute the Cucumber tests.
9. Adjust Paths and Locators:
Adapt paths, element locators, and assertions based on your application's structure.
10. Enhance the Framework:
Add features like reporting, parallel execution, and additional steps.
Install Cucumber plugins for your IDE to aid in feature file writing.
72
CODE
Dependencies (Maven):
<!-- Selenium -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
73
public LoginPage(WebDriver driver)
{ this.driver = driver;
}
public void openLoginPage(String url) {
driver.get(url);
}
public void enterUsername(String username) {
WebElement usernameField = driver.findElement(By.id("username"));
usernameField.sendKeys(username);
}
public void enterPassword(String password) {
WebElement passwordField =
driver.findElement(By.id("password"));
passwordField.sendKeys(password);
}
75
Then User should see an error message
StepDefinitions.java (Cucumber Step Definitions):
package step_definitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import pages.LoginPage;
77
@Then("User should be logged in successfully")
public void user_should_be_logged_in_successfully()
{
// Add assertions based on your application behavior
// For example, assert that a welcome message is displayed
}
@After
public void tearDown() {
driver.quit();
}
}
RUNNING THE TESTS
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestSuite">
<test name="CucumberTests">
<classes>
<class name="io.cucumber.testng.CucumberRunner"/>
</classes>
</test>
</suite>
RESULT
78
Thus, the BDD framework with Selenium,TestNG and Cucumber was executed successfully
79