我在从Excel表格中获取数据时遇到了空指针异常。

huangapple go评论68阅读模式
英文:

I am getting Null pointer Exception while fetching data from the excel sheet

问题

public class ContactUsFormTest {

    WebDriver driver;

    @BeforeMethod
    public void run() {
        System.setProperty("webdriver.chrome.driver", "Driver Path");
        driver = new ChromeDriver();
        driver.get("URL");
        driver.manage().deleteAllCookies();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test(dataProvider = "contactUs")
    public void contactUs(String firstname, String preference, String lastname, String email, String text, String phone) throws InterruptedException {
        driver.findElement(By.id("first_name")).sendKeys(firstname);
        // 下拉菜单处理
        Select sel = new Select(driver.findElement(By.id("preference")));
        sel.selectByVisibleText(preference);
        driver.findElement(By.id("last_name")).sendKeys(lastname);
        driver.findElement(By.id("email")).sendKeys(email);
        driver.findElement(By.id("textarea")).sendKeys(text);
        driver.findElement(By.id("phone")).sendKeys(phone);
        Thread.sleep(2000);
        driver.findElement(By.name("submit")).click();
        Thread.sleep(3000);
        // 验证
        Assert.assertTrue(driver.getTitle().contains("Successful submission"), "Page title verified-Submission UnSuccessful");
        System.out.println("Page title verified-Successful submission");
    }

    @DataProvider(name = "contactUs")
    public String[][] formData() throws Exception {
        Thread.sleep(3000);
        ExcelDataConfig eData = new ExcelDataConfig("Excel sheet path");
        int rows = eData.getRowCount(0);
        String[][] data1 = new String[rows][6];
        for (int i = 0; i < rows; i++) {
            data1[i][0] = eData.getData(0, i, 0); // 姓氏
            data1[i][1] = eData.getData(0, i, 1); // 偏好
            data1[i][2] = eData.getData(0, i, 2); // 名字
            data1[i][3] = eData.getData(0, i, 3); // 电子邮件
            data1[i][4] = eData.getData(0, i, 4); // 文本
            data1[i][5] = eData.getData(0, i, 5); // 电话
        }
        return data1;
    }
}

错误信息:

[Utils] [ERROR] [Error] java.lang.NullPointerException
at dataDrivenFramework.dataDrivenFramework.ExcelDataConfig.getData(ExcelDataConfig.java:31)
at dataDrivenFramework.dataDrivenFramework.ContactUsFormTest.formData(ContactUsFormTest.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source);

这是 ExcelDataConfig 类:

public class ExcelDataConfig {
    XSSFWorkbook wb;
    XSSFSheet sheet1;

    // 构造函数
    public ExcelDataConfig(String excelpath) {
        try {
            File file = new File(excelpath);
            FileInputStream fis = new FileInputStream(file);
            wb = new XSSFWorkbook(fis);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public String getData(int sheetNumber, int row, int column) {
        sheet1 = wb.getSheetAt(sheetNumber);
        String data = sheet1.getRow(row).getCell(column).getStringCellValue();
        return data;
    }

    public int getRowCount(int sheetIndex) {
        int row = wb.getSheetAt(sheetIndex).getLastRowNum();
        row = row + 1;
        return row;
    }
}

我不知道为什么会出现这个错误。

英文:

Code:

public class ContactUsFormTest {
WebDriver driver;
@BeforeMethod
public void run()
{
System.setProperty(&quot;webdriver.chrome.driver&quot;, &quot;Driver Path&quot;);
driver=new ChromeDriver();
driver.get(&quot;URL&quot;);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test(dataProvider=&quot;contactUs&quot;)
public void contactUs(String firstname,String preference,String lastname,String email,String text,String phone) throws InterruptedException
{
driver.findElement(By.id(&quot;first_name&quot;)).sendKeys(firstname);
//drop down handling
Select sel = new Select(driver.findElement(By.id(&quot;preference&quot;)));
sel.selectByVisibleText(preference);
driver.findElement(By.id(&quot;last_name&quot;)).sendKeys(lastname);
driver.findElement(By.id(&quot;email&quot;)).sendKeys(email);
driver.findElement(By.id(&quot;textarea&quot;)).sendKeys(text);
driver.findElement(By.id(&quot;phone&quot;)).sendKeys(phone);
Thread.sleep(2000);
driver.findElement(By.name(&quot;submit&quot;)).click();
Thread.sleep(3000);
//Validation
Assert.assertTrue(driver.getTitle().contains(&quot;Successful submission&quot;), &quot;Page title verified-Submission UnSuccessful&quot;);
System.out.println(&quot;Page title verified-Successful submission&quot;);
}
@DataProvider(name=&quot;contactUs&quot;)
public String[][] formData() throws Exception
{
Thread.sleep(3000);
ExcelDataConfig eData=new ExcelDataConfig(&quot;Excel sheet path&quot;);
int rows=eData.getRowCount(0);
String[][] data1=new String[rows][6];
for(int i=0;i&lt;rows;i++)
{
data1[i][0]=eData.getData(0, i, 0);//first name
data1[i][1]=eData.getData(0, i, 1);//preference
data1[i][2]=eData.getData(0, i, 2);//last name
data1[i][3]=eData.getData(0, i, 3);//email
data1[i][4]=eData.getData(0, i, 4);//text
data1[i][5]=eData.getData(0, i, 5);//phone
}
return data1;
}

}

I am fetching the data from the excel sheet while performing test I am getting below error.

Error:

[Utils] [ERROR] [Error] java.lang.NullPointerException
at dataDrivenFramework.dataDrivenFramework.ExcelDataConfig.getData(ExcelDataConfig.java:31)
at dataDrivenFramework.dataDrivenFramework.ContactUsFormTest.formData(ContactUsFormTest.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

Here is ExcelDataConfig class:

public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet1;
//Constructor
public ExcelDataConfig(String excelpath) {
try {
File file=new File(excelpath); 
FileInputStream fis=new FileInputStream(file);
wb=new XSSFWorkbook(fis);
} 
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public String getData(int sheetNumber,int row,int column) {
sheet1=wb.getSheetAt(sheetNumber);
String data=sheet1.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex)
{
int row=wb.getSheetAt(sheetIndex).getLastRowNum();
row=row+1;
return row;
}

}

I have no clue why I am getting this.

答案1

得分: 0

有许多可能性。所请求的工作表可能不存在。或者行也可能不存在。甚至单元格也可能不存在。你应该添加空值检查。

public String getData(int sheetNumber, int row, int column) {
    sheet1 = wb.getSheetAt(sheetNumber);
    if (sheet1 == null) {
        throw new IllegalArgumentException("工作表编号 " + sheetNumber + " 不存在。");
    }
    if (sheet1.getRow(row) == null) {
        throw new IllegalArgumentException("工作表 " + sheetNumber + " 的行 " + row + " 不存在。");
    }
    if (sheet1.getRow(row).getCell(column) == null) {
        throw new IllegalArgumentException("工作表 " + sheetNumber + " 的行 " + row + " 和列 " + column + " 的单元格不存在。");
    }
    String data = sheet1.getRow(row).getCell(column).getStringCellValue();

    return data;
}

尝试了解一下空指针异常及其修复方法

英文:

There are many possiblities. The requested sheet may not exist. Or the row. Or the cell. You should add null checks.

public String getData(int sheetNumber,int row,int column) {
sheet1=wb.getSheetAt(sheetNumber);
if (sheet1 == null) {
throw new IllegalArgumentException(&quot;Sheet number &quot; + sheetNumber + &quot; does not exist.&quot;
}
if (sheet1.getRow(row) == null) {
throw new IllegalArgumentException(&quot;Row &quot; + row + &quot; in sheet &quot; + sheetNumber + &quot; does not exist.&quot;
}
if (sheet1.getRow(row).getCell(column) == null) {
throw new IllegalArgumentException(&quot;Cell &quot; + column + &quot; in sheet &quot; + sheetNumber + &quot; and row &quot; + row + &quot; does not exist.&quot;
}
String data=sheet1.getRow(row).getCell(column).getStringCellValue();
return data;
}

Try to learn about NullpointerExceptions and how to fix them.

huangapple
  • 本文由 发表于 2020年9月7日 19:29:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63776731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定