硒中的空指针异常

时间:2016-12-22 10:51:14

标签: java selenium selenium-webdriver

try {
           tch (IOException e) {   
            System.out.println("Test d");    
        }   

当我运行上面的代码时,我得到了线程“main”

中的exception.Exception
  

test.testing.main上的java.lang.NullPointerException(testing.java:28)

我正在尝试从excel访问数据并运行测试用例。

我是java和selenium的新手。 如何解决此问题。 请帮忙

无法理解代码中的错误在哪里......

2 个答案:

答案 0 :(得分:1)

据我所知,您正在尝试从excel文件中读取每行的数据并将其传递给 runTest(row.getCell(1).toString(),row.getCell(2).toString());方法

所以这是你完成的完整代码 -

try {
        // Open the Excel file
        FileInputStream fis = new FileInputStream("D:\\Workspace\\test\\src\\test\\testdata.xls");
        // Access the required test data sheet
        HSSFWorkbook wb = new HSSFWorkbook(fis);
        HSSFSheet sheet = wb.getSheet("testdata");
        int rowNumber=0;

         Iterator<Row> rowIterator = sheet.iterator();

            // Traversing over each row of XLSX file
                while (rowIterator.hasNext())
                {                       
                    System.out.println("Running test case "+sheet.getRow(rowNumber).getCell(0).getStringCellValue());
                // Run the test for the current test data row
                runTest(sheet.getRow(rowNumber).getCell(0).toString(),sheet.getRow(rowNumber).getCell(1).toString());

                rowNumber++;
              // To check row cell is not empty
               if(sheet.getRow(rowNumber)==null)
                {
                     break;
                }
            }

         wb.close();
        fis.close();
    } 
catch (IOException e) 
{
        System.out.println("Test data file not found");
   } 

答案 1 :(得分:0)

for应该从0而不是1开始,但您可以尝试使用iterator

根据您的需要调整以下代码

try {
    // Open the Excel file
    FileInputStream fis = new FileInputStream("D:\\Workspace\\test\\src\\test\\testdata.xls");
    // Access the required test data sheet
    HSSFWorkbook wb = new HSSFWorkbook(fis);
    HSSFSheet sheet = wb.getSheet("testdata");

    Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) { // cycle throuh all rows
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            if (cellIterator.hasNext()) { //change to while if you need all columns, otherwise if you need the first column leave as it is...
                Cell cell = cellIterator.next();
                System.out.println("Running test case " + cell.getStringCellValue());
            }
        }
    }            
} catch (IOException e) {
    System.out.println("Test data file not found");
}   
finally
{
    if (fis != null)
    fis.close();
}

您还可以使用以下方法检查列的类型:

String tmp = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
    tmp = cell.getNumericCellValue() + "";
    break;
case Cell.CELL_TYPE_STRING:
    tmp = cell.getStringCellValue();
    break;
// case Cell.<other types>: ... ; break;
}