Keyword Driven Framework-Getting Error java.lang.NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am new to Keyword Driven approach for selenium. I am getting NullPointerException while running below ExecuteTest.java
Folder Structure
Folder structure
Object.txt
Object.txt
TestCase.xlsx
TestCase.xlsx
Error Screenshot
Screenshot1
Screenshot2
Adding Debug screenshots
screenshot1
screenshot2
screenshot3
ReadGuru99Excel.java
import org.apache.poi.ss.usermodel.Sheet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadGuru99ExcelFile {
public Sheet readExcel (String filePath,String fileName, String sheetName)throws IOException{
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook guru99Workbook = null;
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx")){
guru99Workbook = new XSSFWorkbook(inputStream);
} else if(fileExtensionName.equals(".xls")) {
guru99Workbook = new HSSFWorkbook(inputStream);
}
Sheet guru99Sheet =guru99Workbook.getSheet(sheetName);
return guru99Sheet;
}
}
ReadObject.Java
package operation;
import java.util.Properties;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.File;
public class ReadObject {
Properties p = new Properties();
public Properties getObjectRepository()throws IOException{
InputStream stream = new FileInputStream(new File (System.getProperty("user.dir")+"\\src\\objects\\object.txt"));
p.load(stream);
return p;
}
}
UIOperation.java
package operation;
import org.openqa.selenium.WebDriver;
import java.util.Properties;
import org.openqa.selenium.By;
public class UIOperation {
WebDriver driver ;
public UIOperation(WebDriver driver){
this.driver = driver;
}
public void perform(Properties p, String operation, String objectName, String objectType, String value) throws Exception{
System.out.println("");
switch(operation.toUpperCase()){
case "CLICK":
driver.findElement(this.getObject(p, objectName, objectType)).click();
break;
case "SETTEXT":
driver.findElement(this.getObject(p, objectName, objectType)).sendKeys(value);
break;
case "GOTOURL":
driver.get(p.getProperty(value));
break;
case "GETTEXT":
driver.findElement(this.getObject(p, objectName, objectType)).getText();
break;
default:
break;
}
}
private By getObject(Properties p, String objectName, String objectType) throws Exception{
if(objectType.equalsIgnoreCase("XPATH")){
return By.xpath(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("CLASSNAME")){
return By.className(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("NAME")){
return By.name(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("CSS")){
return By.cssSelector(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("LINK")){
return By.linkText(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("PARTIALLINK")){
return By.partialLinkText(p.getProperty(objectName));
}else{
throw new Exception("Wrong object type");
}
}
}
ExecuteTest.java
package testcases;
import java.util.Properties;
import operation.ReadObject;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.MarionetteDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import operation.UIOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import excelExportAndFileIO.ReadGuru99ExcelFile;
public class ExecuteTest {
#Test
public void testLogin()throws Exception{
/**
* System.setProperty("webdriver.gecko.driver", "E:\\Selenium-2017\\geckodriver-v0.18.0-win64\\geckodriver.exe");
* //Now you can Initialize marionette driver to launch firefox
* DesiredCapabilities capabilities = DesiredCapabilities.firefox();
* capabilities.setCapability("marionette", true);
* WebDriver driver = new RemoteWebdriver(capabilities);
*
* WebDriver webdriver = new FirefoxDriver();
**/
WebDriver driver;
System.setProperty("webdriver.chrome.driver","E:\\Selenium-2017\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
ReadGuru99ExcelFile file = new ReadGuru99ExcelFile();
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(driver);
Sheet guru99Sheet = file.readExcel(System.getProperty("user.dir")+"\\test-output","TestCase.xlsx","KeywordFramework");
int rowCount =guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();
System.out.println("first step clear");
for(int i = 0;i<rowCount+1; i++){
Row row =guru99Sheet.getRow(i);
System.out.println("2nd clear");
if(row.getCell(0).toString().length()==0){
System.out.println("4nd clear");
System.out.println(row.getCell(1).toString()+"-----"+row.getCell(2).toString()+"----"+row.getCell(3).toString()+"---"+row.getCell(4).toString());
System.out.println("3rd clear");
operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(), row.getCell(3).toString(), row.getCell(4).toString());
} else
System.out.println("New Testcase->" + row.getCell(0).toString()+"Started");
System.out.println("testerassumption");
}
}
}

First of all, please see this wonderful post about NullPointerException and how to fix it.
In your case, the stacktrace points the NullPointerException to be occuring at line 49 of the code in ExecuteTest.java, which points to this line of code
operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(), row.getCell(3).toString(), row.getCell(4).toString());
The issue here is that when you're trying to convert the contents of the cell in the getCell() method to a String, if there is nothing in the cell, then there would always be a NullPointerException.
You can either place a != null check before every cell or add a " " for every toString() method, like
operation.perform(allObjects, (row.getCell(1)+"").toString(), (row.getCell(2)+"").toString(), (row.getCell(3)+"").toString(), (row.getCell(4)+"").toString());

Related

Why I am getting Data Provider MisMatch error when I try to read from excel file?

I am trying to do data driven testing and I am not able to figure it out why I am getting data mismatch. I am trying to automate just usernames and that is in form of string. Can you please review my code and tell me what I am doing wrong?
Below are two files. one is my main method file and one is my excel config file. I have also attached screenshot of my error. Any help would be appreciated. Thank you.
File1:
`
package loginAdmin;
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.DataProvider;
import org.testng.annotations.Test;
public class PersonateUser {
#Test(dataProvider="testdata")
public void login(String username) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver",
C:\\Users\\abc\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(200, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(200, TimeUnit.SECONDS);
driver.get("www.abc.com/AdminHome.aspx");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtLoginName")).
sendKeys("admin");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtPassword")).
sendKeys("Password");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_cmdContinue")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_lblUserName")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_txtUserName")).
sendKeys(username);
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_btnSearch")).click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_resultsGrid_ctl02_LogInAsUser")).
click();
System.out.println("User is able to login successfully");
driver.findElement(By.xpath("/html/body/form/div[3]/div[3]/div[1]/div[1]/div/div[5]/ul/li[6]/a")).
click();
#DataProvider(name="testdata")
public Object[][] TestDataFeed()
{
ReadExcelFile config = new
ReadExcelFile("C:\\Users\\abc\\eclipseworkspace\\Login\\testdata\\testdata.xlsx");
int rows = config.getRowCount(0);
Object[][] credentials = new Object[rows][2];
for(int i = 0; i < rows; i++)
{
credentials[i][0] = config.getData(0, i, 0);
}
return credentials;
}
}
`
File 2:
` package loginAdmin;
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 wb;
XSSFSheet sheet;
public ReadExcelFile(String excelPath)
{
try
{
File src = new File(excelPath);
FileInputStream fis = new FileInputStream(src);
wb =new XSSFWorkbook(fis);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column)
{
sheet= wb.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex)
{
int row = wb.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}
}
`
Error Screenshot:
Excel File:
You are declaring Object[][] credentials = new Object[rows][2]; but you fill only one column keeping other column empty (null). Hence the dimension of your array does not match the number of arguments your method accepts.
Fix it with changing that line to:
Object[][] credentials = new Object[rows][1];

Copied data paste into String function

Can anyone tell me how to store copied data into String in selenium?
example:
driver.findElement(By.xpath("//*[#id="x")).sendKeys(Keys.CONTROL, "a"));
driver.findElement(By.xpath("//*[#id="xy")).sendKeys(Keys.CONTROL, "c"));
driver.findElement(By.xpath("//*[#id="xy")).sendKeys(Keys.CONTROL, "v"));
I need put the copied data into String
Something like this
String text = driver.findElement(By.xpath("//*[#id="xy")).sendKeys(Keys.CONTROL, "v"));
It seems you want to send ctrl + c keys, which will copy some data in clipboard.. want to store that data in String variable..right?
You have to use Clipboard class to do so..See implementation below...
package resources;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class One {
#Test
public void getClipboardContents() {
String result = "";
System.setProperty("webdriver.chrome.driver", "C://WebDrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
driver.findElement(By.linkText("Images")).sendKeys(copy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText = (contents != null)
&& contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if (hasTransferableText) {
try {
result = (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException ex) {
System.out.println(ex);
ex.printStackTrace();
}
}
System.out.println(result);
}
}
#Starlord ..modify locators as per your need.
#Gaurav Thanks for the code.. I have modified some part of the code.. now I am getting what i want exactly
public void getClipboardContents()
throws UnsupportedFlavorException, IOException {
String result = "google.com";
System.setProperty("webdriver.chrome.driver", "E:\\New folder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
driver.findElement(By.xpath("//*[#id=\"lst-ib\"]")).sendKeys("google.com");
driver.findElement(By.xpath("//*[#id=\"lst-ib\"]")).sendKeys(Keys.CONTROL+"a");
driver.findElement(By.xpath("//*[#id=\"lst-ib\"]")).sendKeys(copy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
String x = (String) contents.getTransferData(DataFlavor.stringFlavor);
System.out.println(x);
int a= result.length();
int b = x.length();
System.out.println(a);
System.out.println(b);
if(a<=b)
{
System.out.println("Matched Character length")
}else
{
System.out.println("Issue In Character length");
}
}
}

Null Pointer Exception if i try to create new Cell and write data into excel

I am trying to write title and price into excel file. I am creating columns but java game me error 'NULL POINTER EXCEPTION' at line number 48, Please help me what is main reason.But if i write at line no 48 ,sheet1.getRow(0).createCell(0).getStringCellValue('Naqash');Then no Null pointer error is showing.
package codeclasses;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class ReadExcel {
List<WebElement> title, prices;
#Test
public void test() throws IOException {
System.setProperty("webdriver.chrome.driver", "h:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://themeforest.net/search/education?referrer=homepage&utf8=%E2%9C%93");
title = driver.findElements(By.xpath("//h3[#class = 'product-list__heading']/a"));
prices = driver.findElements(By.xpath("//p[#class='product-list__price-desktop']"));
File src = new File("./file/Book1.xlsx");
FileInputStream file = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet1 = wb.getSheetAt(0);
for (int i = 0; i < 30; i++) {
int j = 0;
if(sheet1.getRow(i+1)==null){
(48) sheet1.getRow(i+2).createCell(j).setCellValue("Naqash");
sheet1.getRow(i+2).createCell(j+1).setCellValue("Zafar");
}
else{
System.out.println("Cant find the scene");
}
FileOutputStream fileout = new FileOutputStream(src);
wb.write(fileout);
}
}
}
Try to create the row and cell before you insert data into it. For example:
int rowIndex = 0;
int columnIndex = 0;
Row row = sheet1.createRow(rowIndex);
Cell cell = row.createCell(columnIndex);
cell.setCellValue("Naqash");
You can get row by getRow(index) if you have already created it before
The issue is that you never test if the cell is null!
if (cell == null)
{
System.out.println("Cell is Empty in Column:" + cols);
}
else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
//code
}
As a general matter, you should be careful while handling Cell.getCellType() function, since an empty cell could be either null or be a CELL_TYPE_BLANK.
I hope it helped.

The screenshot does not get saved in the directory in Selenium

So I am trying the code where i take a screenshot of a web page. I have used a class to generate random string value and then assign these values to the file name. However when I run the code, it executes completely but however the screenshots are never saved into the directory.
code:
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScreenShot {
private WebDriver driver;
private String BaseUrl;
#Before
public void setUp() throws Exception {
BaseUrl = "https://www.flock.co";
System.setProperty("webdriver.chrome.driver", "C:\\Automation\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
#Test
public void test() throws Exception {
driver.get(BaseUrl);
Thread.sleep(5000);
WebElement emailField = driver.findElement(By.xpath("//div[#id='main-area']//input"));
WebElement Button = driver.findElement(By.xpath("//div[#id='main-area']//button"));
emailField.sendKeys("incomeplete");
Button.click();
}
public static String getRandomString(int length) {
StringBuilder sb = new StringBuilder();
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
for (int i = 0; i < length; i++) {
int index = (int) (Math.random() * characters.length());
sb.append(characters.charAt(index));
}
return sb.toString();
}
#After
public void tearDown() throws Exception {
String fileName = getRandomString(10) + ".png";
String directory = "C:\\Users\\farzan.s.DIRECTI\\Desktop\\LetsKodeIt";
File sourceFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(sourceFile, new File(directory+fileName));
driver.quit();
}
}
However I remove this random string generator and directly specify the directory path in FileUtils, it works.
Code:
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScreenShot {
private WebDriver driver;
private String BaseUrl;
#Before
public void setUp() throws Exception {
BaseUrl = "https://www.flock.co";
System.setProperty("webdriver.chrome.driver", "C:\\Automation\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
#Test
public void test() throws Exception {
driver.get(BaseUrl);
Thread.sleep(5000);
WebElement emailField = driver.findElement(By.xpath("//div[#id='main-area']//input"));
WebElement Button = driver.findElement(By.xpath("//div[#id='main-area']//button"));
emailField.sendKeys("incomeplete");
Button.click();
}
#After
public void tearDown() throws Exception {
File sourceFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(sourceFile, new File(C:\\Users\\farzan.s.DIRECTI\\Desktop\\LetsKodeIt\jfjfnfh.png));
driver.quit();
}
}
You missed "\\" in path.
It should be
FileUtils.copyFile(sourceFile, new File(directory+"\\"+fileName));

Copy all contents in Notepad and paste into Textarea in webpage

Is it possible to copy all contents(Ctrl+A) in the notepad file and paste into Textarea in the webpage using Java /Selenium ?
Solution is as follows:
Code to copy contents of file into a textbox on webpage: This code copies and pastes the contents of one text file into Google search textbox on google.com and hits search button.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CopyFileToTextbox {
public static void main(String[] args) {
File inFile = new File("D:\\path\\to\\notepad\\file\\TextFile1.txt");
StringBuilder targetString = new StringBuilder("");
try {
FileReader fr = new FileReader(inFile);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((s = br.readLine()) != null) {
targetString.append(s);
}
} catch (IOException e) {
e.printStackTrace();
}
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("q")));
driver.findElement(By.name("q")).sendKeys(targetString);
driver.findElement(By.name("btnG")).click();
driver.quit();
}
}

Categories