java+selenium自动化测试实现数据驱动

从Excel中读取数据

public class ExcelDataProvider {
public Object[][] getTestDataByExcel(String fileName, String sheetName)throws IOException {
  File file = new File(fileName);
  FileInputStream inputstream = new FileInputStream(file);
  Workbook wbook = null;
  String fileExtensionName = fileName.substring(fileName.indexOf("."));
  System.out.println(fileExtensionName);
  if (fileExtensionName.equals(".xlsx")) {
   wbook = new XSSFWorkbook(inputstream);
  
  } else if (fileExtensionName.equals(".xls")) {
   wbook = new HSSFWorkbook(inputstream);
  }
  Sheet sheet = wbook.getSheet(sheetName);
  // 通过sheetName生成Sheet对象
  int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
  // 获取当前sheet行数,行号和列号都是从0开始
  List<Object[]> records = new ArrayList<Object[]>();
  // 使用双循环获取excel文件的所有数据(第一行除外)
  for (int i = 1; i < rowCount + 1; i++) {
   Row row = sheet.getRow(i);
   String fields[] = new String[row.getLastCellNum()];
   for (int j = 0; j < row.getLastCellNum(); j++) {
    // 获取单元格数据
    fields[j] = row.getCell(j).getStringCellValue();
   }
   records.add(fields);
  }
  Object[][] results = new Object[records.size()][];
  for (int i = 0; i < records.size(); i++) {
   results[i] = records.get(i);
  }
  return results;
 }
 }
//登录模块
@Listeners(ApiListener.class)
public class login extends BaseTest{
 //数据驱动
 @DataProvider(name="user_name")
 public Object[][] data()throws IOException {
  ExcelDataProvider excel=new ExcelDataProvider();
  return excel.getTestDataByExcel("F://项目实训//data.xlsx","Sheet1");
 }
 //数据驱动 共12条测试用例
 @Test(dataProvider="user_name",description="登录")
 public void testLogin(String u_name,String p_word) throws InterruptedException, IOException {
  //属性文件读取网址
  String opensns_url =ReadProperties.getPropertyValue("base_url");
  //打开页面
  webtest.open(opensns_url);
  //文本框输入
  webtest.click("link=登录");
  webtest.type("name=username", u_name);
  webtest.type("name=password", p_word);
  Thread.sleep(2000);
  webtest.click("xpath=//button[@type='submit']");
  Thread.sleep(2000);
  assertTrue(webtest.isTextPresent("微博"));
  webtest.click("xpath=//span[@class='user-name text-ellipsis']");
  webtest.click("xpath=//div[@event-node='logout']");
 } 
}

你可能感兴趣的:(数据驱动)