问题描述
在 selenium 中从 Excel 读取数据时出现错误 java.lang.NegativeArraySizeException: -1。我使用了 TestNG 框架。我使用@DataProvider 批注从 Excel 中提供数据。
package testCases;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import utilities.ExcelReader;
public class dataProviderExcel {
public static ExcelReader excel = null;
@Test(dataProvider = "create")
public void testData(String username,String password,String is_correct) {
System.out.println(username + "---" + password + "---" + is_correct);
}
@DataProvider(name = "create")
public static Object[][] dataSet() {
if (excel == null) {
excel = new ExcelReader("C:\\Users\\wagho\\OneDrive\\Documents\\saucedemo.xlsx");
}
String sheetname = "logindata";// sheetname from excel
int rows = excel.getRowCount(sheetname);// return the count of rows present in sheet
int colums = excel.getColumnCount(sheetname);// return the count of column present in sheet
Object[][] dataset = new Object[rows - 1][colums];
for (int rowNum = 2; rowNum <= rows; rowNum++) {
for (int colNum = 0; colNum < colums; colNum++) {
dataset[rowNum - 2][colNum] = excel.getCellData(sheetname,colNum,rowNum);
}
}
return dataset;
}
}
下图提供了有关错误的详细信息:
解决方法
NegativeArraySizeException
在尝试创建一个大小为负的数组时被抛出。在您的代码中,异常被抛出
Object[][] dataset = new Object[rows - 1][columns];
请检查您的 Excel 阅读器实用程序。
int rows = excel.getRowCount(sheetname);
要么返回 0
要么返回 1
您尝试调试 excel 阅读器实用程序并观察您获得的行和列的值