简体   繁体   English

尝试使用 Selenium 从 Excel 文件读取数据时出现 NullPointerException

[英]NullPointerException when trying to read data from Excel file using Selenium

I am creating a Selenium project using Maven, wherein I am trying to read 'username' and 'password' from an Excel file (xlsx).我正在使用 Maven 创建一个 Selenium 项目,其中我试图从 Excel 文件 (xlsx) 中读取“用户名”和“密码”。

Here is the code -这是代码-

public class NewTest {

WebDriver driver;


@BeforeTest
public void setup() {
    System.setProperty("webdriver.gecko.driver",Util.FIREFOX_PATH);
    driver = new FirefoxDriver();
    driver.navigate().to(Util.BASE_URL);
}
    

public void readExcel(String filePath, String fileName, String sheetName) throws IOException, InterruptedException {
    File file = new File(filePath+"\\"+fileName);
    FileInputStream fs = new FileInputStream(file);
    Workbook workBook = null;
    String fileExtensionName = fileName.substring(fileName.indexOf("."));
    if (fileExtensionName.equals(".xlsx")) {
        workBook = new XSSFWorkbook(fs); 
    }
    if (fileExtensionName.equals(".xls")) {
        workBook = new HSSFWorkbook(fs);
    }
    Sheet sheet = workBook.getSheet(sheetName);
    int rowCount = sheet.getLastRowNum();
    for (int i = 0; i <= rowCount; i++) {
        Row row = sheet.getRow(i);
        for (int j = 0; j < row.getLastCellNum(); j++) {
            
            driver.findElement(By.xpath("//input[@type='text']")).sendKeys(sheet.getRow(i).getCell(j).getStringCellValue());
            driver.findElement(By.xpath("//input[@type='password']")).sendKeys(sheet.getRow(i).getCell(j+1).getStringCellValue());
            driver.findElement(By.xpath("//input[@type='submit']")).click();
            Thread.sleep(5000);
            String actualTitle = driver.getTitle();
            String expectedTitle = "Home Page";
            SoftAssert sassert = new SoftAssert();
            sassert.assertEquals(actualTitle, expectedTitle);
            sassert.assertAll();
            break;
        }
    }
    
}

@Test
public static void callingFunction() throws IOException, InterruptedException {
    NewTest newTest = new NewTest();
    String filePath = "C:\\Users\\Sitesh\\Desktop";
    newTest.readExcel(filePath, "Book2.xlsx", "Sheet1");
}
}

I am getting the following error -我收到以下错误 -

FAILED: callingFunction
java.lang.NullPointerException
at Guru99_Bank.Guru99_Bank.NewTest.readExcel(NewTest.java:59)
at Guru99_Bank.Guru99_Bank.NewTest.callingFunction(NewTest.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:599)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:822)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.util.ArrayList.forEach(Unknown Source)
at org.testng.TestRunner.privateRun(TestRunner.java:764)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1218)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.runSuites(TestNG.java:1069)
at org.testng.TestNG.run(TestNG.java:1037)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Screenshot of Excel file- Excel文件截图- 在此处输入图像描述

The error I am getting is in this line:我得到的错误是在这一行中:

driver.findElement(By.xpath("//input[@type='text']")).sendKeys(sheet.getRow(i).getCell(j).getStringCellValue()); driver.findElement(By.xpath("//input[@type='text']")).sendKeys(sheet.getRow(i).getCell(j).getStringCellValue());

Issue - Null pointer exception问题 - Null 指针异常

You are trying to access unavailable cell您正在尝试访问不可用的单元格

sheet.getRow(i).getCell(j+1)

This is trying to move toward the next cell from the current one, but that cell doesn't exist这是试图从当前单元格移至下一个单元格,但该单元格不存在

How does Excel reader work? Excel 阅读器如何工作?

Firstly gets the first row and it parses all the cells, one by one sequentially.首先获取第一行,然后依次逐个解析所有单元格。 If no cell is available it goes to the next row.如果没有可用的单元格,它将转到下一行。

If you try to access "two cells" in the same loop (sheet.getRow(i).getCell(j+1)) it will work only if you have data in those cells, if not you'll get an NP exception cause nothing is there.如果您尝试在同一个循环 (sheet.getRow(i).getCell(j+1)) 中访问“两个单元格”,只有当您在这些单元格中有数据时它才会起作用,否则您将得到 NP 异常原因什么都没有。

This picture might clarify it to you这张图片可能会让你明白在此处输入图像描述

Solution:解决方案:

//rows
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
        Row row = sheet.getRow(i);
        //cells
        for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
            // gettingrow cell
            Cell cell = row.getCell(j);
            driver.findElement(By.xpath("//input[@type='text']")).sendKeys(cell.getStringCellValue());
            driver.findElement(By.xpath("//input[@type='password']")).sendKeys(cell.getStringCellValue());
            driver.findElement(By.xpath("//input[@type='submit']")).click();
            Thread.sleep(5000);
            String actualTitle = driver.getTitle();
            String expectedTitle = "Home Page";
            SoftAssert sassert = new SoftAssert();
            sassert.assertEquals(actualTitle, expectedTitle);
            sassert.assertAll();
        }
    }

also - use getPhysicalNumberOfRows() - it return only the rows/cells with data.还 - 使用 getPhysicalNumberOfRows() - 它仅返回包含数据的行/单元格。

Later update for NP exception稍后更新 NP 异常

you need to add the webdriver as a parameter for your excel method.您需要将 webdriver 添加为 excel 方法的参数。 The webdriver gets an instance but when the readExcel method uses is null, so you need to pass the initialized object. webdriver获取一个实例但是readExcel方法使用的时候是null,所以需要传递初始化的object。

Change the method to将方法更改为

public void readExcel(String filePath, String fileName, String sheetName, WebDriver driver)

and this call to这个电话

newTest.readExcel(filePath, "Book2.xlsx", "Sheet1", driver);

and it will work.它会起作用的。

Since you are getting NullPointerException, you are using chaining of methods it is better split into smaller & understand which object is actually null to find reason.由于您得到 NullPointerException,您正在使用方法链,最好将其拆分成更小的并了解哪个 object 实际上是 null 以找到原因。 Without that information, people in the forum may not able to help out没有这些信息,论坛中的人可能无法提供帮助

driver.findElement(By.xpath("//input[@type='text']")).sendKeys(sheet.getRow(i).getCell(j).getStringCellValue());

Something like就像是

Element e = driver.findElement(By.xpath("//input[@type='text']")); Row row = sheet.getRow(i); Cell c = row.getCell(j); String val = c.getStringCellValue();

Here element, row or cell might be null.这里的元素、行或单元格可能是 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM