为什么我为以下代码获取NullPointerException

时间:2019-10-24 05:52:55

标签: selenium-webdriver testng-dataprovider

我正在使用Apache POI API读取excel文件。我写了一个Utility类。但是,当我调用此方法时,出现以下错误。请帮助我找出错误。

public class TestUtil {

    public static int PAGE_LOAD_TIME = 20;
    public static int IMPLICIT_WAIT = 10;
    static Workbook book;`enter code here`
    static Sheet sheet;

    public static Object[][] getTestData(String sheetName){
        FileInputStream file = null;
        try {
                file = new FileInputStream("/home/khawer/eclipse-workspace/DemoSite/src/main/java/com/qa/demo/testdata/testdata.xlsx");
                book = WorkbookFactory.create(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        sheet = book.getSheet(sheetName);
        Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];

        for(int i = 0; i < sheet.getLastRowNum(); i++) {

            for(int j = 0; j < sheet.getRow(0).getLastCellNum(); j++) {

                data[i][j] = sheet.getRow(i + 1).getCell(j).toString();
            }   
        }

        return data;
   }

}
[Utils] [ERROR] [Error] java.lang.NullPointerException
    at com.qa.demo.util.TestUtil.getTestData(TestUtil.java:38)
    at com.qa.demo.testcases.ContactsTest.getDemoData(ContactsTest.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:74)

1 个答案:

答案 0 :(得分:0)

就像inferno提到的那样,请检查第38行,因为我们无法在提到的代码中猜到第38行。

可能的原因是, 1.错误的路径或excel选项卡(如果单个excel中存在多个选项卡) 2.如果纸张完全空白 3.如果行的顶部或行之间有空白行。