WebDriver和TestNG,使用EXcel做数据驱动

上一篇 / 下一篇  2015-02-28 09:45:33

使用Excel作为数据驱动,将TestNG和Webdriver结合起来使用
代码如下
package com.test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.util.ExcelData;
import com.util.GetProperties;

public class TestAttend {
private WebDriver driver;
 private String baseUrl;
 private boolean acceptNextAlert = true;
 private StringBuffer verificationErrors = new StringBuffer();
 private final static Log log = LogFactory.getLog(TestMainPlan.class);
 
 @BeforeClass
 public void setUp() throws Exception {

   //初始化登录系统
System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
driver = new FirefoxDriver();
baseUrl = GetProperties.readValue("webUrl");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl + "/Login2.aspx");
//登录操作
driver.findElement(By.id("txtName")).clear();
driver.findElement(By.id("txtName")).sendKeys(GetProperties.readValue("userName"));
driver.findElement(By.id("txtPWD")).clear();
driver.findElement(By.id("txtPWD")).sendKeys(GetProperties.readValue("passWord"));
driver.findElement(By.id("btnSave")).click(); 
 }
 
 
 @Test(dataProvider = "attendance")
 public void testAttendance(Map<String, String> data) throws Exception {
 String temp_str="";   
 Date dt = new Date(); 
 
 //选择xx
driver.findElement(By.id(data.get("xx").trim())).click();
 
//进入xx页面
driver.findElement(By.xpath("//div[@id='UpdatePanel2']/ul/li[9]/a/span")).click();
driver.findElement(By.linkText("xx")).click();
 
 
//切换iframe
     driver.switchTo().frame(driver.findElement(By.id("ifr")));
     Thread.sleep(6000);
     
   //设置查询的参数
driver.findElement(By.id("ORDER_ID_3")).sendKeys(data.get("xx"));
Assert.assertEquals(data.get("xx").trim(), driver.findElement(By.id("sect_SectionId")).getAttribute("value"), 
            "xx");
new Select(driver.findElement(By.id("sect_Line"))).selectByVisibleText(data.get("xx").trim());
new Select(driver.findElement(By.id("sect_Model"))).selectByVisibleText(data.get("xx").trim());
new Select(driver.findElement(By.id("sect_Class"))).selectByVisibleText(data.get("xx").trim());
new Select(driver.findElement(By.id("sect_plan_status"))).selectByVisibleText("xx"); 
         
//xx日期验证
 
driver.findElement(By.id("btnFind")).click();
 
 
 
 
 }
 
 
 
 @DataProvider(name = "attendance")
 public Iterator<Object[]> data() throws Exception{
 
 return (Iterator<Object[]>)new ExcelData("attendance","attendance");
 
 }//此函数用于实现Excel数据驱动的遍历,有多少行Excel数据,函数testAttendance就运行多少次
 


@AfterClass
 public void tearDown() throws Exception {
   driver.quit();
   String verificationErrorString = verificationErrors.toString();
  
 }

 private boolean isElementPresent(By by) {
   try {
     driver.findElement(by);
     return true;
   } catch (NoSuchElementException e) {
     return false;
   }
 }

 private boolean isAlertPresent() {
   try {
     driver.switchTo().alert();
     return true;
   } catch (NoAlertPresentException e) {
     return false;
   }
 }

 private String closeAlertAndGetItsText() {
   try {
     Alert alert = driver.switchTo().alert();
     String alertText = alert.getText();
     if (acceptNextAlert) {
       alert.accept();
     } else {
       alert.dismiss();
     }
     return alertText;
   } finally {
     acceptNextAlert = true;
   }
 }
}




package com.util;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class ExcelData 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;

/*
* 在TestNG中由@DataProvider(dataProvider = "name")修饰的方法
* 取Excel时,调用此类构造方法(此方法会得到列名并将当前行移到下以后)执行后,转发哦
* TestNG自己的方法中去,然后由它们调用此类实现的hasNext()、next()方法
* 得到一行数据,然后返回给由@Test(dataProvider = "name")修饰的方法,如此
* 反复到数据读完为止
* @param filepath Excel文件名
* @param casename 用例名
*/
public ExcelData(String filepath, String casename){
try{
File directory = new File(".");
   String ss = "unit.";
   book = Workbook.getWorkbook(new File(directory.getCanonicalFile() + "\\resources\\" +
   ss.replaceAll("\\.", Matcher.quoteReplacement("\\")) + filepath + ".xls"));
   this.sheet = book.getSheet(casename);
   
   //得到行数
   this.rowNum = sheet.getRows();
   Cell[] c = sheet.getRow(0);
   this.columnNum = c.length;
   columnName = new String[c.length];
   for(int i = 0; i < c.length; i++){
   columnName[i] = c[i].getContents().toString();
   
   }
   
   //当前行数
   this.curRowNo ++;
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public boolean hasNext() {
/*方法功能:是否下一条数据
* 如果行数为0即空sheet或者当前行数大于总行数
* 就关闭对excel的操作返回false,否则返回true
*/
if(this.rowNum ==0 || this.curRowNo >= this.rowNum){
try{
book.close();
}catch(Exception e){
e.printStackTrace();
}
return false;
}else{
return true;
}
}

@Override
public Object[] next() {
/*
* 方法功能:得到并返回下一行数据
* 使用for将一行的数据放入TreeMap中(Treemap默认按照Key值升序排列,HashMap
* 没有排序),然后将Map装入Objeect[]并返回,且将curRowNo当前行下移
*/
Cell[] c = sheet.getRow(this.curRowNo);
Map<String, String> s = new TreeMap<String, String>();
for(int i = 0; i< this.columnNum; i++){
String temp = "";
try{
temp = c[i].getContents().toString();
}catch(ArrayIndexOutOfBoundsException ex){
temp = "";
}
s.put(this.columnName[i], temp);
}
Object r[] = new Object[1];
r[0] = s;
this.curRowNo ++;
return r;
}

@Override
public void remove() {
throw new UnsupportedOperationException("remove unsupported");
}

}


TAG:

 

评分:0

我来说两句

Open Toolbar