SELENIUM TEST NG FRAMEWORK CODE

 FOLDER STRCTURE






BASE PAGE


package pageObjects;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.support.PageFactory;


public class BasePage {


public WebDriver driver;

public BasePage(WebDriver driver)

{

PageFactory.initElements(driver,this);

}


}

-------------------
DASHBOARD

package pageObjects;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class Dashboard extends BasePage {

public Dashboard(WebDriver driver) 
{
super(driver);
}
@FindBy(xpath="//a[normalize-space()='Dashboard']")
WebElement dashboard;
@FindBy(xpath="//a[normalize-space()='Sign out']")
WebElement clkLogout;
public Boolean verifyDashboardPage()
{
Boolean isDashDisplayed =dashboard.isDisplayed();
return isDashDisplayed;
}
public void clickLogout()
{
clkLogout.click();
}


}

--------------------------------------
HOME PAGE

package pageObjects;

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.FindBy;
import org.openqa.selenium.support.PageFactory;

public class HomePage extends BasePage {
//1) Create constructor and add PageFactory class -  PageFactory is not required
public HomePage(WebDriver driver)
{
super(driver);
}
//2) Add WebElements
@FindBy(xpath = "//a[normalize-space()='My Account']")
WebElement linkMyAcc;
//3) Add Action Methods
public void clickMyAccLink()
{
linkMyAcc.click();
}
}


--------------------------------------------

LOGIN PAGE

package pageObjects;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class LoginPage extends BasePage {
public LoginPage(WebDriver driver)
{
super(driver);
}
@FindBy (xpath ="//input[@id='username']")
WebElement textUsername;
@FindBy (xpath ="//input[@id='password']")
WebElement textPassword;
@FindBy (xpath ="//input[@name='login']")
WebElement clickLogin;
public void setUsername(String username)
{
textUsername.sendKeys(username);
}
public void setPassword(String password)
{
textPassword.sendKeys(password);
}
public void clickLoginButton()
{
clickLogin.click();
}


}

---------------------------------------

REGISTRATION PAGE

package pageObjects;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class RegistrationPage extends BasePage {
public RegistrationPage(WebDriver driver)
{
super(driver);
}


@FindBy(xpath="//input[@id='reg_email']")
WebElement textEmailAdd;
@FindBy (xpath="//input[@id='reg_password']")
WebElement textPassword;
@FindBy (xpath="//input[@name='register']")
WebElement clkRegister;
@FindBy(xpath="//p[contains(text(),'Hello')]")
WebElement loginMess;
//Action Class
public void setEmailAddress(String email)
{
textEmailAdd.sendKeys(email);
}
public void setPassword(String password)
{
textPassword.sendKeys(password);
}
public void clickRegister()
{
clkRegister.click();
}
public String getConfirmationMsg()
{
String welcomeMessage =loginMess.getText().substring(0, 5);
return welcomeMessage;
}

}

--------------------------------------------------------------

BASE CLASS

package testBase;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.lang3.RandomStringUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.apache.logging.log4j.Logger; //Imp for logger
import org.apache.logging.log4j.LogManager; //Imp for logger

public class BaseClass {
public static WebDriver driver;
public Properties p;
public Logger logger; //log4j


@SuppressWarnings("deprecation")
@Parameters({"os","browser"})
@BeforeClass
public void setup(String os, String browser) throws IOException
{
p = new Properties();
FileInputStream fis = new FileInputStream(".//src//test//resources//property.properties");
p.load(fis);
logger=LogManager.getLogger(this.getClass());
if (p.getProperty("ExecutionMode").equals("remote"))
{
DesiredCapabilities capabilities = new DesiredCapabilities();
// Select Operating System
if (os.equalsIgnoreCase("windows"))
{
capabilities.setPlatform(Platform.WIN11);
}
else if (os.equalsIgnoreCase("mac"))
{
capabilities.setPlatform(Platform.MAC);
}
else
{
System.out.println("No Matching OS");
return;
}
//Select Browser
switch(browser.toLowerCase())
{
case "chrome": capabilities.setBrowserName("chrome"); break;
case "edge": capabilities.setBrowserName("edge"); break;
default: System.out.println("Not matching browser"); return; 
}
driver= new RemoteWebDriver (new URL("http://192.168.0.106:4444/wd/hub"),capabilities);
}
if(p.getProperty("ExecutionMode").equals("local"))
{
switch(browser.toLowerCase()) 
{
case "chrome": driver = new ChromeDriver(); break;
case "firefox": driver=new FirefoxDriver(); break;
default: System.out.println("Incorrect Browser Name"); return;
}
}
//driver = new ChromeDriver();
driver.get(p.getProperty("URL"));
//driver.get("https://practice.automationtesting.in/");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
}
@AfterClass
public void tearDown()
{
driver.close();
}
public String randomString()
{
String generatedString =RandomStringUtils.randomAlphabetic(7);
return generatedString;
}
public String randomAplhaNumeric()
{
String generatedString =RandomStringUtils.randomAlphabetic(4);
String generatedNumber= RandomStringUtils.randomNumeric(4);
return generatedString+"@!#"+generatedNumber;
public String captureScreenshot(String tname)
{
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd.HH.mm");
Date dt = new Date();
String timestamp =df.format(dt);

TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
File sourceFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
String targetFilePath = ".\\screenshots" +tname + "_" + timestamp +".png";
File targetFile = new File(targetFilePath);
sourceFile.renameTo(targetFile);
return targetFilePath;
}

}


--------------------------------------------------------------------

TC-001

package testCases;


import java.time.Duration;


import org.apache.commons.lang3.RandomStringUtils;

import org.apache.hc.core5.util.Timeout;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.Test;


import pageObjects.BasePage;

import pageObjects.HomePage;

import pageObjects.RegistrationPage;

import testBase.BaseClass;


public class TC_001_VerifyRegistration extends BaseClass {


@Test

public void verifyRegistration()

{


logger.info("-----Execution started for TC verifyRegistration-----" );

try {

HomePage hp = new HomePage(driver);

hp.clickMyAccLink();

logger.info("Clicked on MyAccountLink");

RegistrationPage rp = new RegistrationPage(driver);

logger.info("Entering username and password");

rp.setEmailAddress(randomString()+"@gmail.com");

rp.setPassword(randomAplhaNumeric());

logger.info("Entered username and password");

rp.clickRegister();

logger.info("Clicked on Register button");

String loginMess =rp.getConfirmationMsg();

Assert.assertEquals (loginMess,"Hello" );

logger.info("Verified the title of the page");

}

catch(Exception e)

{

logger.error("Test failed due to:" +e);

logger.debug("Debug logs");

Assert.fail();

}

}


}


-----------------------
TC-002

package testCases;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

import pageObjects.Dashboard;
import pageObjects.HomePage;
import pageObjects.LoginPage;
import testBase.BaseClass;

public class TC_002_VerifyLogin extends BaseClass 
{

@Test
public void testLoginfunctionality()
{
logger.info("-----TC_002_VerifyLogin execution started----");
try {
HomePage hp = new HomePage(driver);
hp.clickMyAccLink();
logger.info("Clicked on MyAccountLink");
LoginPage lp = new LoginPage(driver);
lp.setUsername(p.getProperty("Username"));
lp.setPassword(p.getProperty("Password"));
lp.clickLoginButton();
logger.info("Clicked on Login button");
Dashboard db = new Dashboard(driver);
Boolean dashboardDisplayed=db.verifyDashboardPage();
Assert.assertTrue(dashboardDisplayed);
logger.info("-----TC_002_VerifyLogin execution completed----");
}
catch(Exception e)
{
logger.error("Following exception occured"+ e);
Assert.assertTrue(false);
}
}

}
-----------------------------
TC -003

package testCases;

import org.testng.Assert;
import org.testng.annotations.Test;

import pageObjects.Dashboard;
import pageObjects.HomePage;
import pageObjects.LoginPage;
import testBase.BaseClass;
import utilities.DataProviders;

public class TC_003_VerifyLoginDD extends BaseClass {
@Test(dataProvider="LoginData", dataProviderClass=DataProviders.class)
public void LoginDDTest(String Username, String Password, String Exp)
{
logger.info("----TC_003_VerifyLoginDD Execution Started----");
try 
{
HomePage hp = new HomePage(driver);
hp.clickMyAccLink();
LoginPage lp = new LoginPage(driver);
lp.setUsername(Username);
lp.setPassword(Password);
lp.clickLoginButton();
Thread.sleep(4000);
Dashboard db = new Dashboard(driver);
Boolean dashboardDisplayed=db.verifyDashboardPage();
if (Exp.equalsIgnoreCase("Valid"))
{
if(dashboardDisplayed==true)
{
db.clickLogout();
Assert.assertTrue(true);
}
else
{
Assert.assertTrue(false);
}
}
if (Exp.equalsIgnoreCase("Invalid"))
{
if(dashboardDisplayed==true)
{
db.clickLogout();
Assert.assertTrue(false);
}
else
{
Assert.assertTrue(true);
}
}
} catch(Exception e)
{
logger.error("Exception is" +e);
Assert.assertTrue(false);
}
logger.info("----TC_003_VerifyLoginDD Execution Completed----");
}


}
--------------------
UTILITIES- DATA PROVIDERS

package utilities;

import java.io.IOException;

import org.testng.annotations.DataProvider;

public class DataProviders {
public static void main(String[]args) throws IOException
{
DataProviders dp=new DataProviders();
String excelData[][]=dp.getLoginData();
//Fetch data from 2D Array
/*for(int r=0; r<=1; r++)
{
for(int c=0; c<=2; c++)
{
System.out.print(excelData[r][c]);
}
System.out.println();
}*/
}
@DataProvider(name="LoginData")
public String[][] getLoginData() throws IOException
{
// Create ExcelUtils object for calling methods
ExcelUtils eu = new ExcelUtils();
int rowCount =eu.getRowCount(".//testData//LoginCredentials.xlsx", "sheet1");
//System.out.println(rowCount);
int cellCount =eu.getCellCount(".//testData//LoginCredentials.xlsx", "sheet1");
//System.out.println(cellCount);
// Create 2D Array to store data from Excel
String loginData[][]= new String [rowCount][cellCount];
for(int r=1; r<=rowCount; r++)
{
for(int c=0; c<cellCount; c++)
{
loginData[r-1][c] =eu.getCellData(".//testData//LoginCredentials.xlsx", "sheet1", r, c);
}
}
return loginData; //returning two dimensional array
}

}

-------------------------------

EXCEL UTILS

package utilities;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {

public  int getRowCount(String fileLocation, String sheetName) throws IOException
{
FileInputStream fis =new FileInputStream(fileLocation);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet =book.getSheet(sheetName);
int rowCount =sheet.getLastRowNum();
book.close();
fis.close();
return rowCount;
}
public int getCellCount(String fileLocation, String sheetName) throws IOException
{
FileInputStream fis = new FileInputStream(fileLocation);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet =book.getSheet(sheetName);
XSSFRow row =sheet.getRow(1);
int cellCount =row.getLastCellNum();
return cellCount;
}
public  String getCellData(String fileLocation, String sheetName, int rowNum, int colNum) throws IOException
{
FileInputStream fis =new FileInputStream(fileLocation);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet =book.getSheet(sheetName);
XSSFRow row =sheet.getRow(rowNum);
XSSFCell cell= row.getCell(colNum);
String data =cell.toString();
book.close();
fis.close();
return data;
}
public  void putCellData(String fileLocation, String sheetName, int rowNum, int cellNum, String data) throws IOException
{
FileInputStream fis =new FileInputStream(fileLocation);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet =book.getSheet(sheetName);
XSSFRow row =sheet.getRow(rowNum);
XSSFCell cellNumber=row.createCell(cellNum);
cellNumber.setCellValue(data);
FileOutputStream fos = new FileOutputStream(fileLocation);
book.write(fos);
book.close();
fis.close();
fos.close();
}

}

--------------------------
EXCEL REPOR TMANAGER


package utilities;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;

import testBase.BaseClass;

public class ExtentReportManager implements ITestListener {

public ExtentSparkReporter  sparkReporter;
public ExtentReports  extent;
public ExtentTest  test;
public void onStart(ITestContext testContext)
{
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Date dt = new Date();
String currentDateTimestamp =df.format(dt);
String repName= "Test-Report-"+ currentDateTimestamp + ".html";
sparkReporter = new ExtentSparkReporter(".\\reports\\"+repName);
    extent = new ExtentReports();
    extent.attachReporter(sparkReporter);
}
public void onTestSuccess(ITestResult result)
{
test= extent.createTest(result.getTestClass().getName());
test.log(Status.PASS,result.getName()+"got successfully executed");
}
public void onTestFailure(ITestResult result)
{
test= extent.createTest(result.getTestClass().getName());
test.log(Status.FAIL,result.getName()+"got failed");
String imgPath = new BaseClass().captureScreenshot(result.getName());
test.addScreenCaptureFromPath(imgPath);
}
public void onFinish(ITestContext testContext)
{
extent.flush();
// Code to open the report directly after execution
//code to mail the report automatically after the execution - Dependencies need to be added
}

}

------------------------------------





No comments:

Post a Comment