selenium自动化测试中,采用jxl实现参数化(从Excel中读取数据)

声明:本文在http://www.cnblogs.com/liu-ke/p/4223807.html文章基础上稍作修改,并增加了简单的测试调用代码

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.ArrayList; 
import org.testng.Assert;
import jxl.*;
 
 /**
  * Excel放在Data文件夹下

* Excel命名方式:测试类名.xls

* Excel的sheet命名方式:测试方法名

* Excel第一行为Map键值

* 代码参考郑鸿志的Blog * {@link www.zhenghongzhi.cn/post/42.html} * @ClassName: ExcelDataProvider * @Description: TODO(读取Excel数据) */ public class ExcelDataProvider{ private Workbook book = null; private Sheet sheet = null; private int rowNum = 0; private int currentRowNo = 0; private int columnNum = 0; private String[] columnnName; //重构构造函数,将待测试类名和方法名传入函数 public ExcelDataProvider(String classname, String methodname) { try { int dotNum = classname.indexOf("."); if (dotNum > 0) { classname = classname.substring(classname.lastIndexOf(".") + 1, classname.length()); } //从/data文件夹下读取以类名命名的excel文件 String path = "data/" + classname + ".xls"; InputStream inputStream = new FileInputStream(path); book = Workbook.getWorkbook(inputStream); //取sheet sheet = book.getSheet(methodname); rowNum = sheet.getRows(); Cell[] cell = sheet.getRow(0); columnNum = cell.length; columnnName = new String[cell.length]; for (int i = 0; i < cell.length; i++) { columnnName[i] = cell[i].getContents().toString(); } this.currentRowNo++; } catch (Exception e) { e.printStackTrace(); Assert.fail("unable to read Excel data"); } } //判断Excel表中是否存在下一行数据 public boolean hasNext() { if (this.rowNum == 0 || this.currentRowNo >= this.rowNum) { try { book.close(); } catch (Exception e) { e.printStackTrace(); } return false; } else { // sheet下一行内容为空判定结束 if ((sheet.getRow(currentRowNo))[0].getContents().equals("")) return false; return true; } } //读取Excel中某一行数据,并为下一行做准备 public List getdata_list() { Cell[] c = sheet.getRow(this.currentRowNo); List list = new ArrayList(); for (int i = 0; i < this.columnNum; i++) { String temp = ""; try { temp = c[i].getContents().toString(); } catch (ArrayIndexOutOfBoundsException ex) { temp = ""; } if(temp != null&& !temp.equals("")) list.add(temp); } this.currentRowNo++; return list; } public void remove() { throw new UnsupportedOperationException("remove unsupported."); } }

以下是简单的测试调用代码:

import java.util.List;

import Test.ExcelDataProvider;

public class TestClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String class_name = "Login";
		String method_name = "jd_login";
		ExcelDataProvider excel_driver = new ExcelDataProvider(class_name, method_name);
		
		String ErrorUser = "";
		String ErrorPwd = "";
		String RightUser = "";
		String RightPwd = "";
		String RUser = "";
			while(excel_driver.hasNext() == true)
			{
				List info_list = excel_driver.next(); 
				int info_size = info_list.size();
			
				for(int i=0; i

读取的Excel文件中有5列,共4行数据,通过以上方法成功实现了selenium的数据参数化,并成功运用到实际测试脚本中

刚开始接触java,调用程序写的比较笨拙,望见谅,欢迎多提改进意见

你可能感兴趣的:(selenium)