必须@SpringBootTest,并且继承AbstractTestNGSpringContextTests
@SpringBootTest(classes = App.class)
public class DemoTest extends AbstractTestNGSpringContextTests
数据驱动
@DataProvider(name = "testData")
private Object[][] data() throws IOException {
// Read Excel
ExcelUtil excelUtil = new ExcelUtil();
// Set Excel file path
String path = excelUtil.getTestDataFilePath("/src/main/resources/testdata/order.xlsx");
excelUtil.setStartReadPos(0);
rowList = excelUtil.readExcel(path);
int rowCount = rowList.size();
int columnCount = rowList.get(0).getLastCellNum(); //根据表头,获取列数
Object[][] records = new Object[rowCount][];
for (int i = 1; i < rowCount; i++) { //不读取表头内容
Row row = rowList.get(i);
records[i] = new Object[columnCount];
for (int j = 0; j < columnCount; j++) {
records[i][j] = excelUtil.getCellValue(row.getCell(j));
}
}
return records;
}
ExcelUtil --> readExcel
public List<Row> readExcel(String xlsPath) throws IOException {
//扩展名为空时,
if (xlsPath.equals("")) {
throw new IOException("文件路径不能为空!");
} else {
File file = new File(xlsPath);
if (!file.exists()) {
throw new IOException("文件不存在!");
}
}
//获取扩展名
String ext = xlsPath.substring(xlsPath.lastIndexOf(".") + 1);
try {
if ("xls".equals(ext)) { //使用xls方式读取
return readExcelXls(xlsPath);
} else if ("xlsx".equals(ext)) { //使用xlsx方式读取
return readExcelXlsx(xlsPath);
} else { //依次尝试xls、xlsx方式读取
out("您要操作的文件没有扩展名,正在尝试以xls方式读取...");
try {
return readExcelXls(xlsPath);
} catch (IOException e1) {
out("尝试以xls方式读取,结果失败!,正在尝试以xlsx方式读取...");
try {
return readExcelXlsx(xlsPath);
} catch (IOException e2) {
out("尝试以xls方式读取,结果失败!\n请您确保您的文件是Excel文件,并且无损,然后再试。");
throw e2;
}
}
}
} catch (IOException e) {
throw e;
}
}
注意:
如果不继承AbstractTestNGSpringContextTests,会导致@Autowired的服务为null。 具体原因还没有找到,不过应该是TestNG的@BeforeClass,@BeforeTest的执行顺序有关。在Spring容器初始化前就执行了,导致@Autowired的服务均为null。
TODO
传入参数过多,要修改private Object[][] data() 函数,传入对象。