Cannot fetch the data from excel sheet in automation testing - java

Please check the code suggest correction:
package com.framework;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DataDriveFramework {
public void readExcel(String filePath, String fileName, String sheetName) throws IOException {
File file = new File(filePath+"\\"+fileName);
FileInputStream fis = new FileInputStream(file);
Workbook loginWorkbook=null;
String fileExtension=fileName.substring(fileName.indexOf("."));
if(fileExtension.equals(".xlsx"))
{
loginWorkbook=new XSSFWorkbook(fis);
}
else if(fileExtension.equals("xls"))
{
loginWorkbook=new HSSFWorkbook(fis);
}
Sheet loginSheet=loginWorkbook.getSheet(sheetName);
int rowCount=loginSheet.getLastRowNum()-loginSheet.getFirstRowNum();
for(int i=1;1<rowCount+1;i++)
{
Row row=loginSheet.getRow(i);
String username=row.getCell(0).getStringCellValue();
String password=row.getCell(0).getStringCellValue();
test(username,password);
}
}
public void test(String username, String password)
{
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
String baseURL="https://accounts.google.com";
driver.get(baseURL);
driver.findElement(By.id("identifierId")).sendKeys(username);
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div/c-wiz/div/div[2]/div/div[2]/div/div[1]/div/div/button/span")).click();
driver.findElement(By.xpath("//*[#id=\"password\"]/div[1]/div/div[1]/input")).sendKeys(password);
driver.findElement(By.xpath("//*[#id=\"passwordNext\"]/div/button/span")).click();
driver.quit();
}
public static void main(String[] args)throws IOException {
DataDriveFramework readFile=new DataDriveFramework();
String filePath="C:\\Users\\Shefali\\eclipse-workspace\\DataDriveFramework\\TestExcelSheet\\";
readFile.readExcel(filePath, "DataDriven.xls", "Sheet1");
}
}
The code is to fetch the data from excel sheet and login automatically.But I am getting an error--
"Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.ss.usermodel.Workbook.getSheet(String)" because "loginWorkbook" is "null"
at com.framework.DataDriveFramework.readExcel(DataDriveFramework.java:31)
at com.framework.DataDriveFrame.main(DataDriveFrame.java:60)"

You missed a dot '.' in the below line in readExcel() method:
else if(fileExtension.equals("xls"))
it should be like:
else if(fileExtension.equals(".xls"))

Related

Unable to call the parameters from one class-method to another class-method

I have tried with the below code having two classes once is Class1-TestData and Method1-excel(),
And another call to access the parameters Class2-AdminLoginAction and Method2-Admin_Login().
Here is the problem with I need to call the string parameters like UID and PWD as I marked in the Screenshot attached. But the script showed some error and was unable to access it. So, How can I solve this problem, Am I going to the right approach or any other way? Please do need full as soon as possible.
Script image for two classes
import java.io.IOException;
import java.util.Date;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class AdminLoginAction extends TestData{
WebDriver d;
Date currentdate = new Date();
String Screenshotdate = currentdate.toString().replace(" ", "-").replace(":", "-");
ExtentSparkReporter spark = new ExtentSparkReporter("ExtentReport.html");
ExtentReports extent = new ExtentReports();
#Test()
public void Admin_Login() throws InterruptedException, IOException {
TestData excel = new TestData();
extent.attachReporter(spark);
ExtentTest test = extent.createTest("Launch browswer and access the WeClean Login page");
test.log(Status.PASS, "Launch browser success...!!!");
test.pass("Verified launching browser");
System.setProperty("webdriver.chrome.driver", "D:\\backup\\selenium\\chromedriver.exe");
d = new ChromeDriver();
d.manage().window().maximize();
d.get(URL);
Utils.CaptureScreenshot(d, Screenshotdate + "_Login.png");
d.findElement(By.id("loginUser")).sendKeys(UID);
d.findElement(By.id("password")).sendKeys(PWD);
d.findElement(By.id("loginButton")).click();
Thread.sleep(5000);
Utils.CaptureScreenshot(d, Screenshotdate + "_HomePage.png");
test.log(Status.PASS, "Admin Logged in Successful");
test.pass("Verified Admin logged in");
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
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;
import org.testng.annotations.Test;
public class TestData{
public void excel() throws IOException {
String filePath = System.getProperty("user.dir")+"\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(inputStream);
XSSFSheet sheet=wb.getSheet("Admin_inputs");
XSSFRow row2=sheet.getRow(1);
XSSFCell cell=row2.getCell(0);
double UID= cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
String PWD = cell2.getStringCellValue();
}
You can try like this:
public class TestData {
double UID;
String PWD;
public void excel() throws IOException {
String filePath = System.getProperty("user.dir") + "\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheet("Admin_inputs");
XSSFRow row2 = sheet.getRow(1);
XSSFCell cell = row2.getCell(0);
UID = cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
PWD = cell2.getStringCellValue();
}
}
In Admin_Login() method, am just printing UID and PWD, change the code according to your requirement:
public class AdminLoginAction extends TestData {
#Test()
public void Admin_Login() throws InterruptedException, IOException {
// TestData excel = new TestData(); // you don't need to create this object because you are already inheriting `TestData` class.
excel(); // before using UID and PWD you have to call excel() method.
System.out.println(UID);
System.out.println(PWD);
}
}

How to call a method in every test which is in the base class and has a data provider in selenium

I have been trying to integrate browser stack with my selenium scripts. As part of which i have added desired capabilities in my 'getBrowser' method with data provider in the Base class. As i want to run my scripts in multiple browsers. The browsers list is in "getData" method in Base class.
How can i call the getBrowser method in my testcases and have the getData(browsers list) defined in only the base class. This what i have done and its not right. i have added my base class and the test script.
Base.getBrowser(Platform platform, String browserName, String browserVersion); this line is were i am stuck.
Any help would be appreciated. Thanks
package com.gale.precision.FundVisualizer.core;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.DataProvider;
import org.openqa.selenium.Platform;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Base {
//public static WebDriver driver = null;
public static WebDriver driver;
public static String DriverPath = System.getProperty("user.dir") + "//" + "Drivers";
public static String DirectoryPath = System.getProperty("user.dir");
public static Properties prop = new Properties();
public static InputStream input = null;
public static final String USERNAME = "antonyprabhu1";
public static final String AUTOMATE_KEY = "xHRMpqxgD8sn3e3sr75s";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
#DataProvider(name = "EnvironmentDetails")
public static void getBrowser(Platform platform, String browserName, String browserVersion) throws MalformedURLException
{
DesiredCapabilities capability = new DesiredCapabilities();
capability.setPlatform(platform);
capability.setBrowserName(browserName);
capability.setVersion(browserVersion);
capability.setCapability("browserstack.debug", "true");
driver = new RemoteWebDriver(new URL(URL), capability);
try {
input = new FileInputStream(DirectoryPath + "//" + "config" + "//" + "app.properties");
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
public static void closeBrowser() {
driver.quit();
}
}
package comparison;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Platform;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.gale.precision.FundVisualizer.core.Base;
import com.gale.precision.FundVisualizer.core.ExtentReport;
import com.gale.precision.FundVisualizer.pageObject.Comparison;
import com.gale.precision.FundVisualizer.pageObject.InvestmentsSearch;
#SuppressWarnings("unused")
public class AddedInvestmentDisplay extends ExtentReport {
/*============================================================================================================================
Test case : Verify that already selected Investments for comparison does not show up
======================================================================================*/
#Test(testName = "Comparison: Verify an already selected Investment for comparison does not show up in search")
public void verifyAddedInvestmentDisplay() throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(Platform platform, String browserName, String browserVersion);
InvestmentsSearch.login(Base.driver);
InvestmentsSearch.InvestmentsLink(Base.driver).click();
JavascriptExecutor jse = (JavascriptExecutor) Base.driver;
jse.executeScript("window.scrollBy(0,750)", "");
InvestmentsSearch.ViewResults(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.firstCheckBox(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
//Base.clickingStaleElements(Comparison.firstCheckBox(Base.driver));
//Comparison.firstCheckBox(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.analyzeOrCompare(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Comparison.firstSearchResult(Base.driver).click();
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Assert.assertEquals(Comparison.emptySearchResult(Base.driver).isDisplayed(), true);
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
#AfterClass
public void tearDown()
{
Base.closeBrowser();
}
}
I could resolve this issue by passing the parameters in the #test method
#Test(testName="Comparison: Verify adding an index in the comparison", dataProvider = "EnvironmentDetails",dataProviderClass = BrowsersDataProvider.class)
public void verifyAddingIndex(Platform platform, String browserName, String browserVersion) throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(platform,browserName,browserVersion);
InvestmentsSearch.login(Base.driver);
like

When i am trying to run the code then an error message is occur

When i am trying to run below mention code the an error message is occur. In my code i am trying to execute logout function. for this logout function, i have prepared a excel where logout xpath properly store. but when i am trying to execute this code an error message is occur.error message is Element is not clickable at point (1155, 20). Other element would receive the click
package com.rmspl.multiplemethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class MethodSet {
static WebElement element;
public void login (String username,String password,String nr,WebDriver fd) {
fd.get("http://117.247.65.9/vms_test");
fd.manage().window().maximize();
WebElement E1 = fd.findElement(By.name("j_username"));
E1.sendKeys(username);
WebElement E2 = fd.findElement(By.name("j_password"));
E2.sendKeys(password);
WebElement E3 = fd.findElement(By.name("log"));
E3.click();
}
public void clickLink(String xPath,String nr,String nr1,WebDriver fd){
element = fd.findElement(By.xpath(xPath));
element.click();
}
public void Select(String xPath,String val,String nr1,WebDriver fd){
Select sel = new Select(fd.findElement(By.xpath(xPath)));
sel.selectByValue(val);
}
}
package com.rmspl.multiplemethod;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestDriver {
static WebElement element;
public static void main(String[] args) throws BiffException, IOException, NoSuchMethodException, SecurityException,
IllegalAccessException,IllegalArgumentException, InvocationTargetException {
MethodSet mt = new MethodSet();
System.setProperty("webdriver.chrome.driver","C:\\Users\\Arijit Mohanty\\Desktop\\chromedriver.exe");
WebDriver fd = new ChromeDriver();
FileInputStream fis = new FileInputStream("C:\\Users\\Arijit Mohanty\\Desktop\\Bangla\\HybridDatasheet.xls");
Workbook WB = Workbook.getWorkbook(fis);
Sheet Sh = WB.getSheet("Sheet2");
int rows = Sh.getRows();
int cols = Sh.getColumns();
for (int i = 1; i<rows; i++)
{
String methodname = Sh.getCell(0, i).getContents();
String data1 = Sh.getCell(1, i).getContents();
String data2 = Sh.getCell(2, i).getContents();
String data3 = Sh.getCell(3, i).getContents();
Method m1 = mt.getClass().getMethod(methodname, String.class,String.class,String.class, WebDriver.class);
m1.invoke(mt,data1,data2,data3,fd);
}
}
}
You need to wait for loading_bg till goes off the screen. please update the method clickLink as given below. please try and let us know.
public void clickLink(String xPath,String nr,String nr1,WebDriver fd){
new WebDriverWait(fd, 90).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading_bg")));
element = fd.findElement(By.xpath(xPath));
element.click();
}

How to continue execution from where the excel stopped?

I am working with excel using selenium web driver where username and password is passed is taken from excel and passed to application,pass/fail status is written back to excel.During exceptions such as no element found etc the execution stops. How to continue execution from the point where it stopped in the excel. Following is my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;
public class Checkbox2 {
static WebDriver driver;
private static String filePath = "C:\\TEST DATA\\Users\\test.xlsx";
private static String sheetName = "Sheet1";
static File fl= new File(filePath);
public static void main(String[] args) throws InterruptedException, EncryptedDocumentException, InvalidFormatException
{
System.setProperty("webdriver.firefox.bin", "C:\\Users\\vijayab\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://qa-bnymellon.correctnet.com/bnymellon/release10/me.get?DPS.home");
// driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/a[1]")).click();
try {
FileInputStream fis = new FileInputStream("C:\\Users\\vijayab\\Documents\\Work\\TEST DATA\\Users\\test.xlsx");
Workbook wb;
wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheet("Sheet1");
for(int count=0;count<=sheet.getLastRowNum();count++)
{
Row row = sheet.getRow(count);
System.out.println("\n----------------------------");
System.out.println("Running test case " + count);
runTest(count, sheet, row.getCell(0).toString(),row.getCell(1).toString(),row,wb);
}
fis.close();
driver.close();// Closing the firefox driver instance
} catch (IOException e) {
System.out.println("Test data file not found");
}
}
public static void runTest(int count,Sheet sheet,String name,String mailid, Row row, Workbook wb) throws InterruptedException, InvalidFormatException, IOException
{
System.out.println("Inputing name: "+name+" and mailid: "+mailid);
driver.findElement(By.name("USERNAME")).sendKeys(name);
driver.findElement(By.name("PASSWORD")).sendKeys(mailid);
driver.findElement(By.name("SIGNIN")).click();
//driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
try{
if(driver.findElements(By.name("loginForm")).size() == 0){
System.out.println("Valid credentials"+count);
driver.findElement(By.name("DISCLAIMER")).click();
driver.findElement(By.id("ACCOUNTDOCUMENTS")).click();
driver.findElement(By.xpath("//*[contains(text(),'Account Profile')]")).click();
Thread.sleep(3000);
driver.switchTo().frame("FDX1");
driver.switchTo().frame("frame2-1");
Thread.sleep(4000);
driver.findElement(By.name("chk")).click();
driver.findElement(By.name("PROFILE_UPDATE")).click();
Alert alert = driver.switchTo().alert();
alert.accept();
driver.get("<logout url>");
int cellindex = 3;
WriteToFile.setExcelData(wb,filePath, sheetName, row.getRowNum(),cellindex, "PASS");
System.out.println("Inputted name: "+name+" and mailid: "+mailid);
Thread.sleep(2000);
}
else if(driver.findElements(By.name("loginForm")).size() == 0){
driver.findElement(By.name("loginForm")).isDisplayed();
System.out.println("Inputted name: "+name+" and mailid: "+mailid + "does not exist");
int cellindex = 3;
WriteToFile.setExcelData(wb,filePath, sheetName, row.getRowNum(),cellindex, "Fail");
return;
}
}
catch(UnreachableBrowserException e){
System.out.println("Exception occured");
}
}
}
There could be different ways to handle it. What i would suggest is below one.
Add another Catch block to catch Exceptions in method runTest. Return aBoolenvalue as false in case of exceptions. Based on the return type, decide on how to proceed further in you For Loop. I Guess this should help you solve the problem. Please let me know in case of any queries.

Read and write to the same Excel file

package jexcel.jxl.nimit;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.LabelCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class ExcelJxl {
public static void main(String[] args) throws WriteException, IOException, BiffException{
String S="D:\\nimit.xls";
ExcelJxl.WriteFile(S);
}
public static void WriteFile(String path) throws IOException, WriteException, BiffException{
Workbook wb=Workbook.getWorkbook(new File(path));
Sheet sheet=wb.getSheet(0);
String s1=null;
String s2=null;
Cell c1=sheet.getCell(0,0);
Cell c2=sheet.getCell(1,0);
if (c1.getType() == CellType.LABEL)
{
LabelCell lc = (LabelCell) c1;
s1 = lc.getString();
}
if (c2.getType() == CellType.LABEL)
{
LabelCell lb = (LabelCell) c2;
s2 = lb.getString();
}
String s3=s1+s2;
WritableWorkbook copy=Workbook.createWorkbook(new File("D:\\demo.xls"),wb);
WritableSheet Wsheet = copy.getSheet(0);
Label l1=new Label(0,0,s1);
Wsheet.addCell(l1);
Label l2=new Label(1,0,s2);
Wsheet.addCell(l2);
Label l3 = new Label(2, 0,s3);
Wsheet.addCell(l3);
copy.write();
copy.close();
}
}
I'm trying to learn how to read and write to the same Excel file.
I'm taking two strings from one file and putting in the other.
How to put the content into the same file?
I'm creating a new file and then I'm putting the contents.
How to read and write to the same text file?
How to overcome this problem?
read-write lock: http://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock

Categories

Resources