如何在以下代码中修复NullPointerException?

时间:2017-09-28 08:20:47

标签: java database excel nullpointerexception testng

我一直在寻找从书籍Selenium WebDriver by Rajeev Gupta中的MS Excel文件访问测试数据的方法。但是,当我运行此代码时,它在许多语句中显示Null-Pointer Exception,我对如何修复此错误感到困惑。我在Selenium中使用TestNG框架来测试代码并使用名称 CurrencyConverter.xlsx 保存Excel文件。下面给出了excel测试数据的屏幕截图。此Excel文件的工作表名称为 CurrencyConversion

enter image description here

以下是代码:

package excelPackage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ExcelClass {

    private String excelFilePath;
    private int rowCount;
    private int columnCount;
    private Connection conn;
    private Statement stmt;
    private ResultSet resultSet;

    public ExcelClass(String filepath)
    {
        excelFilePath=filepath;
    }

    public List<HashMap<String, Object>> read(String sql)
    {
        ResultSet resultSet = this.executeSql(sql,true); //LINE 32
        List<HashMap<String, Object>> recordSet = convertResultSetToList(resultSet);
        closeConnection();
        return recordSet;
    }

    public void update(String sql)
    {
        this.executeSql(sql, false);
        closeConnection();
    }

    private ResultSet executeSql(String sql, boolean read)
    {
        // TODO Auto-generated method stub
        String absolutePath=getAbsoluteFilePath(excelFilePath); //LINE 47
        conn=getConnection(absolutePath,read);
        ResultSet resultSet = executeQueryOnExcel(conn,sql);
        return resultSet;
    }
    private String getAbsoluteFilePath(String excelFilePath) {
        // TODO Auto-generated method stub
        String filepath=getClass().getResource(excelFilePath).getFile(); //LINE 54
        filepath=filepath.replaceFirst("/", "");
        return filepath;
    }

    private Connection getConnection(String excelFilePath, boolean read) {
        String username="";
        String password="";
        String connString;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            if(read) {
                connString=this.getReadConnectionString(excelFilePath);
            }else {
                connString=this.getWriteConnectionString(excelFilePath);
            }
            conn=DriverManager.getConnection(connString, username, password);
        }catch(ClassNotFoundException e) {
            Assert.assertTrue(false,"Incorrect driver class");
        }catch(SQLException e) {
            Assert.assertTrue(false,"Connection with excel db failed");
        }
        return conn;
    }
    private String getReadConnectionString(String excelFilePath) {
        // TODO Auto-generated method stub
        String connString="jdbc:odbc:DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ="+excelFilePath+"";
        return connString;
    }

    private String getWriteConnectionString(String excelFilePath) {
        // TODO Auto-generated method stub
        String connString="jdbc:odbc:DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ="+excelFilePath+";ReadOnly=0;";
        return connString;
    }

    private ResultSet executeQueryOnExcel(Connection conn, String sql) {
        // TODO Auto-generated method stub
        try{
            stmt=conn.createStatement();
            stmt.execute(sql);
            resultSet=stmt.getResultSet();
        }catch(SQLException e) {
            Assert.assertTrue(false, "Failed to execute sql query.");
        }
        return resultSet;
    }
    private List<HashMap<String, Object>> convertResultSetToList(ResultSet resultSet) {
        // TODO Auto-generated method stub
        int rowCtr = 0;
        ResultSetMetaData rsmd = getResultSetMetaData(resultSet);
        this.setColumnCount(resultSet);
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
        try {
            while(resultSet.next()) 
            {
                HashMap<String, Object> row = new HashMap<String,Object>(columnCount);
                for(int i=1;i<=columnCount;++i) 
                {
                    row.put(rsmd.getColumnName(i), resultSet.getObject(i));
                }
                rowCtr = rowCtr + 1;
                list.add(row);
            }
        }
        catch(SQLException e) 
        {
            Assert.assertTrue(false,"Failed to convert ResultSet to List.");
        }
        rowCount=rowCtr;
        return list;
    }

    public int getRowCount() {
        return rowCount;
    }

    public int getColumnCount() {
        return columnCount;
    }

    private ResultSetMetaData getResultSetMetaData(ResultSet rs) {
        // TODO Auto-generated method stub
        ResultSetMetaData rsmd = null;
        try {
            rsmd=rs.getMetaData();
        }catch(SQLException e) {
            e.printStackTrace();
        }
        return rsmd;
    }

    private void setColumnCount(ResultSet resultSet) {
        // TODO Auto-generated method stub
        ResultSetMetaData rsmd = getResultSetMetaData(resultSet);
        try {
            columnCount=rsmd.getColumnCount();
        }catch(SQLException e) {
            Assert.assertTrue(false, "Failed to retrieve column count.");
        }
    }

    private void closeConnection() {
        // TODO Auto-generated method stub
        try {
            stmt.close();
            conn.close();
        }catch(SQLException e) {
            Assert.assertTrue(false, "Failed to close Excel DB connection.");
        }
    }

    @Test
    public void testExcelDBRead()
    {
        ExcelClass excelClass = new ExcelClass("./src/ExcelFiles/CurrencyConverter.xlsx");
        String sql = "Select * from [CurrencyConversion$]";
        List<HashMap<String, Object>> resultSet = excelClass.read(sql); //LINE 171
        System.out.println("Row Count:"+excelClass.getRowCount());
        System.out.println("Column Count:"+excelClass.getColumnCount());
        for(int i=0;i<resultSet.size();i++)
        {
            System.out.println(resultSet.get(i).get("Key")+"\t");
            System.out.println(resultSet.get(i).get("KeyName")+"\t");
            System.out.println(resultSet.get(i).get("Amount")+"\t");
            System.out.println(resultSet.get(i).get("FromCurrency")+"\t");
            System.out.println(resultSet.get(i).get("ToCurrency")+"\t");
            System.out.println();
        }
    }

}

这是我在代码中遇到的错误。

FAILED: testExcelDBRead
java.lang.NullPointerException
    at excelPackage.ExcelClass.getAbsoluteFilePath(ExcelClass.java:54)
    at excelPackage.ExcelClass.executeSql(ExcelClass.java:47)
    at excelPackage.ExcelClass.read(ExcelClass.java:32)
    at excelPackage.ExcelClass.testExcelDBRead(ExcelClass.java:171)
    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:108)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:669)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:877)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1201)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:776)
    at org.testng.TestRunner.run(TestRunner.java:634)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:425)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:420)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:385)
    at org.testng.SuiteRunner.run(SuiteRunner.java:334)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1318)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1243)
    at org.testng.TestNG.runSuites(TestNG.java:1161)
    at org.testng.TestNG.run(TestNG.java:1129)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

0 个答案:

没有答案