海鸥一飞 发表于 2018-2-7 15:16:14

selenium 入门学习 (四)

   通过Excel对用例参数进行配置
   pom.xm依赖:
<dependency>
    <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>   Excel读取类:通过迭代器实现,这样比较方便封装,实现Excel读取类型的多态性;这里用的是
Map实现;
public class ExcelIterator implements Iterator<Object[]> {
private Workbook book = null;
private Sheet sheet = null;

private int rowNum = 0;
private int curRowNo = 0;
private int columnNum = 0;
private String[] columnName;
private int singleline = 0;

public ExcelIterator(String filename, String testMethodname) {
    try {
      FileInputStream fs = new FileInputStream(filename);
      this.book = Workbook.getWorkbook(fs);
      this.sheet = book.getSheet(testMethodname);
      this.rowNum = sheet.getRows();
      Cell[] c = sheet.getRow(0);
      this.columnNum = c.length;
      columnName = new String;
      for (int i = 0; i < c.length; i++) {
            columnName = c.getContents().toString();
      }

      if (this.singleline > 0) {
            this.curRowNo = this.singleline;
      } else {
            this.curRowNo++;
      }

    } catch (FileNotFoundException e) {
      System.out.println("文件IO异常");
    } catch (BiffException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
}

@Override
public boolean hasNext() {
    if (this.rowNum == 0 || this.curRowNo >= this.rowNum) {
      book.close();
      return false;
    }
    if (this.singleline > 0 && this.curRowNo > this.singleline) {
      book.close();
      return false;
    }
    return true;
}

@Override
public Object[] next() {
    Cell[] c = sheet.getRow(this.curRowNo);
    Map<String, Object> s = new LinkedHashMap<String, Object>();

    for (int i = 0; i < this.columnNum; i++) {
      String data = c.getContents().toString();
      s.put(this.columnName, data);
    }
    this.curRowNo++;
    return new Object[] { s };
}

@Override
public void remove() {
    // TODO Auto-generated method stub
}
}   读取Excle用例示例:
public class TestDriverData {
    @Test(dataProvider = "test_selenium1")
    public void f(Map<String, String> data) {
      System.out.println("用例标题:" + data.get("comment"));
}

    @DataProvider(name = "test_selenium1")
    public Iterator<Object[]> dataProvider() {
      return new ExcelIterator("D:\\data\\ErShouFangWebDetailTest.xls", "testEsfWebDetail");
    }
}   Excel展示:

   Excel读取执行用例结果:



梦想家 发表于 2018-5-14 16:53:31

:victory:
页: [1]
查看完整版本: selenium 入门学习 (四)