近期学习selenim自动化测试,发现在实际测试过程中,测试数据未与测试脚本进行分离后期的脚本改动非常大,而且脚本数据易用性非常弱。通过apache POI实现excel的数据驱动,可以很好的解决脚本与数据分离的问题。
实现思路:
1、 首先导入poi的第三方jar包,我这里用的是poi
3.7版本jar包。
2、 定一个excel读取类ExcelWorkBook,定义读取方法readExcel,方法返回类型为一个list集合,指定为Stirng[]存储数据。
3、 获得工作簿,然后再获得sheet页,再获得sheet页面中的有效行数。
4、 读取数据,使用双层for循环,外层循环sheet页中的行数,内层循环每一行中的实际列数。
5、 将每一行中的实际列的单元值存储到一个数组中,然后add进入到集合中,返回集合类型,方便读取调用获取到集合中的元素。
6、 通过junit的@Parameter注解完成参数化读取。
此案例中以https://www.worktile.com登录脚本为例进行演示,脚本代码,excle中的测试参数数据如下:
【Excle中的数据内容】
username passWord
xiucaihua lp20105203344
1198874993@QQ.comlp20105203344
Excel读取数据代码
public class ExcelRead {
// 通过workbook读取excel
HSSFWorkbook book;
public static List<String[]> readExcel(String sourceString) {
List<String[]> userList = new ArrayList<String[]>();
try {
InputStream is = new FileInputStream(sourceString);
HSSFWorkbook book = new HSSFWorkbook(is);
// 获取到工作表
HSSFSheet Sheet = book.getSheetAt(0);
// 获取文件的行数
int row = Sheet.getLastRowNum();
// 列表横向取出每一行中列的值
for (int i = 1; i < row; i++) {
HSSFRow rows = Sheet.getRow(i);
// 获得实际的列数
int colNum = rows.getPhysicalNumberOfCells();
String[] temp = new String[colNum];
// 循环每一行的的实际列数,获得列中的值
for (int j = 0; j < colNum; j++) {
String[] temp1 = new String[colNum];
// 获取到每一行的第一个列的值,竖向取值。
String userName = Sheet.getRow(i).getCell(j).getStringCellValue();
temp1[j] = userName;
temp[j] = temp1[j];
}
userList.add(temp);
}
} catch (Exception e) {
e.printStackTrace();
}
return userList;
}
}
webdriver登录脚本代码:
@RunWith(value = Parameterized.class)
public class TestCSVDriver {
WebDriver driver = new FirefoxDriver();
private String username;
private String password;
public TestCSVDriver(String username, String password) {
this.username = username;
this.password = password;
}
@Parameters
public static Collection<String[]> getData() {
List<String[]> userList = ExcelRead.readExcel("D:\\login_TestData.xls");
return userList;
}
@Before
public void setUp() throws Exception {
driver.get(ObjectStore.baseUrl);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
@Test
public void test() {
driver.findElement(By.name("login_name")).clear();
driver.findElement(By.name("login_name")).sendKeys(this.username);
driver.findElement(By.name("login_password")).clear();
driver.findElement(By.name("login_password")).sendKeys(this.password);
driver.findElement(By.xpath(ObjectStore.loginButton)).click();
}
@After
public void tearDown() {
driver.close();}
}