我陷入了空指针异常问题。测试是通过JUnit运行的,但我没能正确调试并找出原因。
测试类
ExcelActions excelActions;
Excel_Import excel_import;
@Test
public void addResultsToExcel() throws InterruptedException {
searchAfterLogin(); // works fine until the next method
excelActions.addToExcel(); //thats where NPE begins...
excel_import.importExcel(excelActions.addToExcel());
}
Excel 操作(Webdriver 部分)
public class ExcelActions extends BaseAction {
public ExcelActions(WebDriver driver) { super(driver); }
public Map<String, Object[]> addToExcel(){
String beforeXpath_pageName = "//*[@id=\"mw-content-
text\"]/div[3]/ul/li[";
String afterXpath_pageName = "]/div[1]/a";
int rowCount ;
rowCount = 20;
Map<String, Object[]> data = new TreeMap<String, Object[]>();
for(int i = 1; i <= rowCount; i++){
String actualXpath_pageName = beforeXpath_pageName + i +
afterXpath_pageName;
String pageName =
driver.findElement(By.xpath(actualXpath_pageName)).getText();
System.out.println(pageName);
data.put("" + i, new Object[]{pageName});
}
return data;
}
}
Excel导入类
public class Excel_Import extends BaseAction {
public Excel_Import(WebDriver driver) { super(driver); }
public void importExcel(Map<String, Object[]> data) {
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Data");
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
//create a row of excel sheet
Row row = sheet.createRow(rownum++);
//get object array of particular key
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if (obj instanceof String)
{
cell.setCellValue((String) obj);
}
else if (obj instanceof Integer)
{
cell.setCellValue((Integer) obj);
}
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new
File("D:\\Projects\\Cucumber\\src\\main\\resources\\ImportedResults.xlsx"));
workbook.write(out);
out.close();
System.out.println("howtodoinjava_demo.xlsx written successfully on
disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
你们能看一下吗?
最佳答案
字段:
ExcelActions excelActions;
未初始化。您应该为其分配一个 ExcelActions 实例,例如:
ExcelActions excelActions = new ExcelActions(someWebDriverMock);
在类中声明一个字段是不够的。您需要为其分配一些特定的对象,否则它将为 null
。
关于java - 将 Web 元素导入 Excel 时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53297393/