0% found this document useful (0 votes)
202 views41 pages

CCS366 Sta Lab Manual

Lab manual Anna university..
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
202 views41 pages

CCS366 Sta Lab Manual

Lab manual Anna university..
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

THE KAVERY ENGINEERING COLLEGE Page :

THE KAVERY ENGINNERING COLLEGE


MECHERI, SALEM – 636453, TAMIL NADU.

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

CCS366 SOFTWARE TESTING


AND AUTOMATION LABORATORY

Student Name:
Year / Semester: III / V
THE KAVERY ENGINEERING COLLEGE Page :

Staff Sign
Awarded
Page No.

Marks
Ex.No. Date Name of the Experiment
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:1

DEVELOP THE TEST PLAN FOR E-COMMERCE WEB APPLICATION

AIM
To Develop the test plan for testing an e-commerce application.

DESCRIPTION

(i) Testing Registration and Login of the Online Shopping Website

 Can a guest purchase product as a guest user?


 Can a guest able to register on the website easily?
 Once registered, can a user able to log in successfully?
 Can a registered user able to view all the products listed on the website?
 Are the user sessions being maintained for the intended time period?
 Is the user’s session timing out and expiring after a defined time?
 Is the registered user able to view and modify its user account information?
 Is the registered user not able to access the user account after logout?

(ii)Testing Search Feature of the Online Shopping Website

 Is the website having multiple filters to search products like., price range, category,
brands, etc.?
 Are relevant Products displaying after applying single or multiple search filters?
 Is there an option to display a fixed number of products on the search page?
 Is there any sort option available on the search page and is that working properly?
THE KAVERY ENGINEERING COLLEGE Page :

 Amazon Search Box Text Box for reference:

(iii)Testing the Product Details Page of the Online Shopping Website

 Is the page displaying all the product information on that page?


 Can a user select different sizes, colors, and quantities of the product?
 Is the page displaying any offers if applicable to the product?
 Is the page displaying the stock information correctly?
 Is the product getting added cart after doing so?

(iv)Testing the Shopping Cart of the e-commerce website

 Is the correct price getting displayed in the shopping cart for the selected product/s?
 Is there an option to apply coupon codes?
 Can a user increase or decrease the quantity of a product from the shopping cart?
 Can a user remove the product from the shopping cart?
THE KAVERY ENGINEERING COLLEGE Page :

RESULT:
Thus the test plan is developed for testing the e-commerce web application.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:2
DESIGN THE TEST CASES FOR TESTING E-COMMERCE APPLICATION

AIM: To Design the test cases for testing the banking application.

DESCRIPTION :

Test cases to check the Login Functionality:


Login page
THE KAVERY ENGINEERING COLLEGE Page :

Test cases to check the Browser Accessibility:

RESULT:
Thus the test cases are developed and tested.
THE KAVERY ENGINEERING COLLEGE Page :

EX.NO.:3

TEST E-COMMERCE APPLICATION &REPORT THE DEFECTS

AIM: To Design the test cases for testing the banking application.

DESCRIPTION :

Banking Application:

#include<stdio.h>
#include<conio.h>
unsigned long amount=25000, deposit, withdraw;
int choice, pin, i; char transaction ='y';
void main()
clrscr();
while (pin != 1097)
{
printf("ENTER YOUR PIN NUMBER: ");
scanf("%d", &pin);
if (pin != 1097)
printf("PLEASE ENTER VALID PASSWORD\n");
}
do
{
printf(" Welcome to ATM Service \n"); printf("1. Check Balance\n");
printf("2. Withdraw Cash\n"); printf("3. Deposit Cash\n"); printf("4. Quit\n");
printf("\n\n");
case 2:
printf("\n ENTER THE AMOUNT: ");
scanf("%lu", &withdraw);
if (withdraw % 100 != 0)
{
printf("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100");
}
else if (withdraw >(amount - 1000))
{
printf("\n INSUFFICENT BALANCE");
}
else
{
amount = amount - withdraw;
printf("\n\n PLEASE COLLECT YOUR CASH");
printf("\n YOUR CURRENT BALANCE =RS.%lu", amount);
THE KAVERY ENGINEERING COLLEGE Page :

}
break;
case 3:
printf("\n ENTER THE AMOUNT: ");
scanf("%lu", &deposit); amount = amount + deposit;
printf(" YOUR BALANCE =RS.%lu", amount);
break;
case 4:
printf("\n THANK YOU USING OUR ATM SERVICES");
break; default:
printf("\n INVALID CHOICE");
}
printf("\n\n\n DO U WISH TO HAVE ANOTHER TRANSCATION?(y/n): ");
fflush(stdin);
scanf("%c", &transaction);
if (transaction == 'n'|| transaction == 'N')
i = 1;
} while (!i);
printf("\n\n THANKS FOR USING OUR ATM SERVICE");
getch();
}

output:

ENTER YOUR PIN NUMBER: 1097


Welcome to ATM Service
1. Check Balance
2. Withdraw Cash
3. Deposit Cash
4. Quit

Enter your choice: 1


YOUR BALANCE =Rs.25000
DO U WISH TO HAVE ANOTHER TRANSCATION?(y/n): Welcome to ATM Service
1. Check Balance
2. Withdraw Cash
3. Deposit Cash
4. Quit
Enter your choice: 2

ENTER THE AMOUNT: 20000 PLEASE COLLECT YOUR CASH


YOUR CURRENT BALANCE =RS.5000
DO U WISH TO HAVE ANOTHER TRANSCATION?(y/n): Welcome to ATM Service
1. Check Balance
2. Withdraw Cash
3. Deposit Cash
THE KAVERY ENGINEERING COLLEGE Page :

4. Quit

Enter your choice: 1


YOUR BALANCE =Rs.5000
DO U WISH TO HAVE ANOTHER TRANSCATION?(y/n): Welcome to ATM Service
1. Check Balance
2. Withdraw Cash
3. Deposit Cash
4. Quit

Enter your choice: 3

ENTER THE AMOUNT: 200 YOUR BALANCE =RS.5200

DO U WISH TO HAVE ANOTHER TRANSCATION?(y/n): Welcome to ATM Service


1. Check Balance
2. Withdraw Cash
3. Deposit Cash
4. Quit

Enter your choice: 1


YOUR BALANCE =Rs.5200
DO U WISH TO HAVE ANOTHER TRANSCATION?(y/n): Welcome to ATM Service
1. Check Balance
2. Withdraw Cash
3. Deposit Cash
4. Quit

Enter your choice: 4

Quit.

Features to be tested:
1. Validity of the card.
2. Withdraw Transaction flow of ATM.
3. Authentication of the user’s.
4. Dispense the cash from the account.
5. Verify the balance enquiry.
6. 6. Change of PIN number.
THE KAVERY ENGINEERING COLLEGE Page :

BUG REPORT:
Bug Id: ATM_003
Bug Description: Invalid Account type selected.
Steps to reproduce:
1. Enter a valid user PIN number.
2. Select the withdraw option on the main menu.
3. Choose the correct type of account (either savings or current account).
Expected Result: Enter the Amount screen displayed
Actual Result: Invalid Account type screen is displayed.
Status : Pass/Fail
Bug-Id Bug Name
ATM_001 Invalid Card
ATM_002 Invalid PIN
ATM_003 Invalid Account type
ATM_004 Insufficient Balance
ATM_005 Transaction Limit
ATM_006 Day limit
ATM_007 Invalid money denominations
ATM_008 Receipt not printed
ATM_009 PIN change mismatch

Bug Id: ATM_001


Bug Description: Invalid card
Steps to reproduce: 1. Keep valid card in the ATM.
Expected Result: Welcome Screen
Actual Result: Invalid card
Status : Pass/Fail

Bug Id: ATM_002


Bug Description: Invalid PIN entered
Steps to reproduce:
1. Keep a valid card in ATM.
2. Enter the authorized PIN.
3. Menu screen should be displayed.
Expected Result: Menu screen displayed
Actual Result: Invalid PIN screen is displayed
Bug Id: ATM_004
Status : Pass/Fail
Bug Description: Insufficient Balance
THE KAVERY ENGINEERING COLLEGE Page :

Steps to reproduce:
1. Menu screen should be displayed.
2. Select the withdraw option.

3. Select the correct type of account.

4. Enter the sufficient amount to withdraw from the account.

5. Dispense the cash screen & amount to be deducted from account

Expected Result: Collect the amount screen displayed


Actual Result: Insufficient balance in the account
Status : Pass/Fail

Bug Id: ATM_005


Bug Description: Withdraw Limit per transaction.
Steps to reproduce:
1. Menu screen should be displayed.
2. Select the withdraw option.

3. Select the correct type of account.

4. Enter sufficient amount to withdraw fromthe account Transaction within the limit.

5. Dispense the cash screen & amount to be deducted from account.

Expected Result: Cash is dispensed and collect the receipt Actual Result:
Transaction limit exceeded screen is displayed Status : Pass/Fail

Bug Id: ATM_006


Bug Description: Withdraw limit per day
Steps to reproduce:
1. Keep a valid card in ATM.
2. Enter the authorized PIN.
3. Enter the amount to withdraw from the account.

4. Amount enter is over the day limit (>40000)

5. Amount enter is over the day limit and display screen is displayed.

Expected Result: Cash is dispensed and collect the receipt.


Actual Result: Day limit exceeded screen is displayed.
Status : Pass/Fail
THE KAVERY ENGINEERING COLLEGE Page :

Bug Id: ATM_007

Bug Description: Amount enter denominations


Steps to reproduce:
1. Keep a valid card in ATM.

2. Enter the authorized PIN.

3. Enter the amount which should be in multiples of 100.

4. Cash Dispenser screen is displayed.

Expected Result: Collect the amount screen is displayed.


Actual Result: Amount enter not in required denominations.

RESULT:

Thus the application is tested and the bug are reported.


THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.: 4

INVENTORY CONTROL SYSTEM

AIM:
To develop Test cases for Inventory control system.

DESCRIPTION:

Test cases for inventory control system.


THE KAVERY ENGINEERING COLLEGE Page :

RESULT:

Thus the test case is developed and tested for inventory control system.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:5 CLIENT SERVER APPLICATION

AIM
To test client server application and record the results.

DESCRIPTION:

Server

1. Create a server socket


2. Wait for client to be connected.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop

Client

1. Create a client socket and establish connection with the server


2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop

Program:

CHAT SERVER

// TCP Chat Server--tcpchatserver.java

import java.io.*;
import java.net.*;
class tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(5555);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept(); System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
THE KAVERY ENGINEERING COLLEGE Page :

while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("\nServer <<< " + CltMsg);
System.out.print("Message to Client : ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
} catch (
Exception E)
{ System.out.println(E.getMessage());
}
}}

Program:

CHAT CLIENT

// TCP Chat Client--tcpchatclient.java


import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{i
f (args.length > 1)
{
System.out.println("Usage: java hostipaddr");
System.exit(-1);
}i
f (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
Clt = new Socket(InetAddress.getByName(args[0]),5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
THE KAVERY ENGINEERING COLLEGE Page :

System.out.println("Type \"end\" to Quit");

while (true)
{
System.out.print("\nMessage to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
SrvMsg = fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}} catch(Exception E)
{
System.out.println(E.getMessage());
}}}

Output
Server Console
$ javac tcpchatserver.java
$ java tcpchatserver
Server started
Client connected
Server <<< hi
Message to Client : hello
Server <<< how r u?
Message to Client :
fine
Server <<< me too
Message to Client : bye
Client Disconnected
Client Console
$ javac tcpchatclient.java
$ java tcpchatclient
Type "end" to Quit
Message to Server : hi
Client <<< hello
Message to Server : how r
u? Client <<< fine
Message to Server : me too
Client <<< bye
Message to Server : end

RESULT:
Thus the program is executed and testing is performed.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO:6
PERFORMANCE TESTING OF E-COMMERCE APPLICATION

AIM: To test the performance of the e-commerce application using jmeter.

DESCRIPTION:

Performance testing metrics:

 Processor Usage: Time spent by the processor to execute non-idle threads.


 Memory use: The available physical memory to process on a system.
 Disk time: It is the time taken by the disk to read or write a request.
 Bandwidth: Bits per second used by a network interface.
 Private bytes: A specific number of bytes allocated to a particular process.
 Committed memory: The amount of virtual memory used.
 Response time: Time between the user’s request and the first response character.
 Throughput: Rate of requests received per second by a network.

1. Adding a Thread Group

 Open the JMeter window.


 The window is divided into two parts. The left side has all the added elements, while the right side has all
the configurations of that element.
 Rename the test plan and save it.
 Let's rename it as the FirstJMeter.
 Right-click on the test plan.
 Go to add -> Threads (Users) -> Thread Group
THE KAVERY ENGINEERING COLLEGE Page :

2. Add an HTTP Request Defaults


 This is done so that multiple HTTP requests can be sent to the same server.
 Right-click on the Thread Group.
 Go to Add -> Config Element -> HTTP Request Defaults.

 In the window that appears, fill the Server Name or IP with the name of the server you want to test. Here,
we have used Simplilearn’s website.
 The next step is to add an HTTP Cookie Manager.
THE KAVERY ENGINEERING COLLEGE Page :

1. Add an HTTP Cookie Manager

 Here we shall support cookies by adding HTTP Cookie Manager to the Thread Group:
 Right-click on the Thread Group.
 Go to Add -> Config Element -> HTTP Cookie Manager

5. Add a View Results in Table Listener


 Listeners are something that is used to provide the outputs of a load test. There are different types of
listeners present in JMeter, and a good deal may be added using plugins.
 The listener we will use here is the Table, as it is comparatively easy to read.
 Right-click on the Thread Group.
 Go to Add -> Listener -> View Results in Table
THE KAVERY ENGINEERING COLLEGE Page :

6. Run the Basic Test Plan


 Save the test plan.
 Click on View Results in Table.
 Click on the Run button (green start button).

RESULT:
Thus the performance Testing is done using JMeter.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO:7
AUTOMATION TESTING OF E-COMMERCE APPLICATIONS

AIM: To Perform the Automation testing of e-commerce applications using Selenium.

DESCRIPTION:

 Setting up Java on your local machine


 Installing and configuring the Eclipse IDE
 Creating your Java project
 Importing Selenium and JUnit dependencies
 Writing a simple UI test script using Java and Selenium WebDriver.

Import the Selenium and JUnit dependencies:

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.3</version>
</dependency>

Write a simple UI Test script using Java and Selenium WebDriver

@BeforeEach
public void setUp() {
System.out.println("*** set up ***");
System.setProperty("webdriver.chrome.driver", "C://development//chromedriver//chromedriver.exe");
webDriver = new ChromeDriver();
}
@AfterEach
public void tearDown() {
System.out.println("*** tear down ***");
webDriver.quit();
}

package selenium;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SauceTest {
private WebDriver webDriver;
THE KAVERY ENGINEERING COLLEGE Page :

@BeforeEach
public void setUp() {
System.out.println("*** set up ***");
System.setProperty("webdriver.chrome.driver",
"C://development//chromedriver//chromedriver.exe");
webDriver = new ChromeDriver();
}
@Test
public void demoFormTest() {
System.out.println("*** test ***");
webDriver.get("https://saucelabs.com/request-demo");
boolean expectedFieldsExist;
try {
webDriver.findElement(By.id("FirstName"));
webDriver.findElement(By.id("LastName"));
webDriver.findElement(By.id("Company"));
expectedFieldsExist = true;
} catch (NoSuchElementException e) {
expectedFieldsExist = false;
}
assertTrue(expectedFieldsExist);
}
@AfterEach
public void tearDown() {
System.out.println("*** tear down ***");
webDriver.quit();
}
}
THE KAVERY ENGINEERING COLLEGE Page :

Result:
Thus the Automation Testing is performed using Selenium.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO:8
AUTOMATION TESTING USING TestNG

AIM: To Perform the Automation testing using TestNG.

DESCRIPTION:

 Create your first TestNG class by right-clicking on the package


 selecting the’ Other’ folder from the ‘New’ option.

 From the wizard modal, select the TestNG folder and select the TestNG class as below
THE KAVERY ENGINEERING COLLEGE Page :

 Click the ‘New’ button and choose any predefined annotations you wish to have in your class as
below:

 Click on finish, and you are ready to start writing your first TestNG class.
THE KAVERY ENGINEERING COLLEGE Page :

Automation Code:

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 {

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());

}
THE KAVERY ENGINEERING COLLEGE Page :

@AfterClass
public void afterClass()
{
driver.quit();
}

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 -->

Below is the referenced console output of the executed test:


THE KAVERY ENGINEERING COLLEGE Page :

 To access the TestNG report, you only need to refresh your project folder.
 A folder as ‘test output’ will be auto-generated.

 Double click on it and you can view your TestNG reports,


 showing the passed and failed methods of the execution as below.

RESULT:
Thus the Automation Testing is performed using TestNG.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO:9
DATA DRIVEN FRAMEWORK ,PAGE OBJECT MODEL using
Selenium and TestNG
AIM: To Perform the Automation testing using Selenium and TestNG.

DESCRIPTION:
 Go to the Eclipse IDE and create a project. Add all the dependencies for TestNG, Selenium and
Apache POI.
 Create a class file to write the functionality.

Program:

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>");
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;
}
}
THE KAVERY ENGINEERING COLLEGE Page :

Running Selenium Tests:

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;
}

Using the Page Object Model pattern in Selenium + TestNG tests

Creating Page Objects

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");
}
}
THE KAVERY ENGINEERING COLLEGE Page :

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);
}

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);
}
}

package com.ontest automation.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();
}
}

package com.ontestautomation.seleniumtestngpom.tests;

public class TestNGPOM {

WebDriver driver;

@BeforeSuite
public void setUp() {

driver = new FirefoxDriver();


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
THE KAVERY ENGINEERING COLLEGE Page :

@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();
}
}

<!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>

Integration of Cucumber with Selenium and TestNG

Add Selenium, TestNG, and Cucumber dependencies to the project

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cucumber.version>7.6.0</cucumber.version>
<selenium.version>4.3.0</selenium.version>
<webdrivermanager.version>5.2.1</webdrivermanager.version>
<testng.version>7.4.0</testng.version>
<apache.common.version>2.4</apache.common.version>
<maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version>
<maven.surefire.plugin.version>3.0.0-M7</maven.surefire.plugin.version>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
</properties>

<dependencies>

<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
</dependency>
THE KAVERY ENGINEERING COLLEGE Page :

<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>

<!-- Selenium -->


<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>

<!-- Web Driver Manager -->


<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
</dependency>

<!-- TestNG -->


<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>

<!-- Apache Common -->


<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>${apache.common.version}</version>
</dependency>

</dependencies>

Add Maven Compiler Plugin and SureFire Plugin

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
THE KAVERY ENGINEERING COLLEGE Page :

<version>${maven.surefire.plugin.version}</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-


instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>CucumberTestNG_Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cucumber.version>7.6.0</cucumber.version>
<selenium.version>4.3.0</selenium.version>
<webdrivermanager.version>5.2.1</webdrivermanager.version>
<testng.version>7.4.0</testng.version>
<apache.common.version>2.4</apache.common.version>
<maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version>
<maven.surefire.plugin.version>3.0.0-M7</maven.surefire.plugin.version>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
</properties>

<dependencies>

<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
</dependency>

<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>

<!-- Selenium -->


<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
THE KAVERY ENGINEERING COLLEGE Page :

<!-- Web Driver Manager -->


<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
</dependency>

<!-- TestNG -->


<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>

<!-- Apache Common -->


<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>${apache.common.version}</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven.surefire.plugin.version}</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
THE KAVERY ENGINEERING COLLEGE Page :

STEP DEFINITION OF THE LOGINPAGE

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.github.bonigarcia.wdm.WebDriverManager;

public class LoginPageDefinitions {

private static WebDriver driver;


public final static int TIMEOUT = 10;

@Before
public void setUp() {

WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
driver.manage().window().maximize();
}

@Given("User is on HRMLogin page {string}")


public void loginTest(String url) {

driver.get(url);

@When("User enters username as {string} and password as {string}")


public void goToHomePage(String userName, String passWord) {

// login to application
driver.findElement(By.name("username")).sendKeys(userName);
driver.findElement(By.name("password")).sendKeys(passWord);

driver.findElement(By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/form/div[3]/button")).submit();

// go the next page

@Then("User should be able to login sucessfully and new page open")


public void verifyLogin() {

String homePageHeading = driver.findElement(By.xpath("//*[@id='app']/div[1]/div[2]/div[2]/div/div[1]/


div[1]/div[1]/h5")).getText();
THE KAVERY ENGINEERING COLLEGE Page :

//Verify new page - HomePage


Assert.assertEquals(homePageHeading,"Employee Information");

@Then("User should be able to see error message {string}")


public void verifyErrorMessage(String expectedErrorMessage) {

String actualErrorMessage = driver.findElement(By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/


div[2]/div/div[1]/div[1]/p")).getText();

// Verify Error Message


Assert.assertEquals(actualErrorMessage,expectedErrorMessage);

@After
public void teardown() {

driver.quit();
}

Create a TestNG Cucumber Runner class in src/test/java

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(tags = "", features = {"src/test/resources/features/LoginPage.feature"}, glue =


{"com.example.definitions"},
plugin = {})

public class CucumberRunnerTests extends AbstractTestNGCucumberTests {

Test Execution through TestNG


THE KAVERY ENGINEERING COLLEGE Page :

Run the tests from TestNG.xml

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


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Cucumber with TestNG Test">
<classes>
<class name="com.example.runner.CucumberRunnerTests"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Cucumber Report Generation:


THE KAVERY ENGINEERING COLLEGE Page :

emailable-report.html

Index.html

RESULT:
Thus the Automation testing is performed using Selenium and TestNG.

You might also like